Laravel 如何在两个独立的数据库中创建迁移关系?

时间:2021-04-21 05:21:25

标签: php laravel laravel-8

我有两个单独的 Laravel 项目和两个单独的数据库。

我在 config/database.php 中连接了这个数据库,它工作正常。

但是现在我需要在产品从数据库 1 到用户从数据库 2 之间创建关系(在数据库 1 中调用卖家)但我需要将此迁移保存在数据库 1 中,我该怎么做?

我试试这个:

Schema::connection('database2')->create('product_seller', function (Blueprint $table) {
    $table->id();

    $table->unsignedBigInteger('product_id');
    $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
    $table->unsignedBigInteger('seller_id');
    $table->foreign('seller_id')->references('id')->on('sellers')->onDelete('cascade');
    $table->primary(['product_id', 'seller_id']);

    $table->timestamps();
});

但在这种情况下,在数据库 2 中创建的表,如果我删除 connection('database2'),我会收到错误,因为我在数据库 1 中没有卖家表,但我这里有 Seller.php 模型连接到用户在数据库 2 中

class Seller extends Model
{
    use HasFactory;

    protected $connection = 'database2';
    protected $table = 'users';
    protected $fillable = [...];
}

0 个答案:

没有答案