如何在数据库中的公共模式之外的不同模式中插入数据。 [LARAVEL]

问题描述 投票:0回答:1

我想在我在laravel迁移中创建的模式中插入数据,但我找不到方法。

有人可以指导吗?

public function up()
{
    DB::statement('CREATE SCHEMA IF NOT EXISTS reports');

    Schema::create('reports.campaign_reports', function (Blueprint $table) 
     {
        $table->bigIncrements('id');
        $table->string('campaign')->nullable();
        $table->string('currency')->nullable();
    });
}

这是我的模特:

class CampaignReport extends Model
{

//    protected $connection = 'schema.reports';

protected $table = 'campaign_reports';

protected $fillable = [
    'campaign',
    'currency'
    ];
}

这就是我如何储蓄:

CampaignReport::create((array) $dataObject);

我收到此错误:

SQLSTATE [42P01]:未定义的表:7错误:关系“campaign_reports”不存在第1行:插入“campaign_reports”(“广告系列”,“货币”,...

enter image description here

php database laravel eloquent migration
1个回答
1
投票

尝试在数据库配置中定义第二个数据库连接:

/** config/database.php */

// ...

  'connections' => [

        'public_schema' => [
            'driver' => 'pgsql',
            'database' => env('DB_DATABASE'),
            // ...
            'schema' => 'public',
        ],

        'reports_shema' => [
            'driver' => 'pgsql',
            'database' => env('DB_DATABASE'),
            // ...
            'schema' => 'reports',
        ],
    ],

// ...

然后,在模型中设置连接(这对于执行Eloquent / Query Builder操作很有用):

class CampaignReport extends Model
{

    protected $connection = 'reports_schema'; // <----

    protected $table = 'campaign_reports';

    protected $fillable = [
            'campaign',
            'currency'
        ];

    // ...
}

当然,当您进行需要在与默认连接不同的连接中运行的迁移时,您必须指定它:

public function up()
{
    DB::statement('CREATE SCHEMA IF NOT EXISTS reports');

    Schema::connection('reports_schema')->create('campaign_reports', function (Blueprint $t)
#           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
     {
        $t->bigIncrements('id');
        $t->string('campaign')->nullable();
        $t->string('currency')->nullable();
    });
}

顺便说一句,将您的.env默认数据库密钥更新为:

DB_CONNECTION=public_schema
© www.soinside.com 2019 - 2024. All rights reserved.