首页 > 解决方案 > Laravel 如何在两个独立的数据库中创建迁移关系?

问题描述

我有两个独立的 Laravel 项目,我有两个独立的数据库。

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

但是现在我需要在 database1 中的产品与 database2 中的用户之间创建关系(在 database1 中调用卖家),但我需要将此迁移保存在 database1 中,我该怎么做?

我试试这个:

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 = [...];
}

标签: phplaravellaravel-8

解决方案


推荐阅读