【问题标题】:How to insert data in different schema other than public schema in database. [LARAVEL]如何在数据库中的公共模式以外的不同模式中插入数据。 [拉拉维尔]
【发布时间】:2019-04-24 15:07:15
【问题描述】:

我想将数据插入到我在 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”(“campaign”、“currency”、...

【问题讨论】:

  • 您想手动存储数据还是用户输入?
  • 我正在点击 google ads api 及其返回给我的数据。我不使用表单或用户输入。只想存储来自该请求的数据。当我在公共方案(默认方式)时它正在工作,但现在我想存储在不同的模式中。

标签: php database laravel eloquent migration


【解决方案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

【讨论】:

  • 但是我应该在我的 env 文件中给出什么?现在是 DB_CONNECTION = pgsql
  • 这是因为 Laravel 需要一个默认连接才能在未指定时使用。在您的迁移中,如果使用使用public 架构的默认连接,我认为这是错误的根源。
  • 顺便说一句,在你的.env:DB_CONNECTION = public_schema'
  • 好吧,我在 database.php 以及迁移和模型中添加了一些东西,但我收到了这个错误:InvalidArgumentException : Database [reports_schema] not configured.
  • @Mohsin 数据库名称必须相同,这就是我在两者中都使用EVN('DB_DATABASE') 的原因
猜你喜欢
  • 2023-01-05
  • 2021-12-22
  • 2017-02-06
  • 1970-01-01
  • 1970-01-01
  • 2017-03-12
  • 1970-01-01
  • 1970-01-01
  • 2020-09-02
相关资源
最近更新 更多