我有两个单独的 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 = [...];
}