两个模式之间的数据透视表



我有两个MySQL模式:

包含"类别"的数据库A。包含"客户"的数据库B

现在,我需要在它们之间创建一个枢轴关系,因此"category_customer"插入到数据库b中。我可以使用经典的pivot表单来创建关系吗?然后添加指向数据库A的外键?

非常感谢。

创建透视表"category_customer"在数据库B中添加指向"类别"的外键。数据库A:

Schema::create('category_customer', function (Blueprint $table) {
$table->unsignedInteger('category_id');
$table->unsignedInteger('customer_id');
$table->foreign('category_id')->references('id')->on('databaseA.categories');
$table->foreign('customer_id')->references('id')->on('databaseB.customers');
});

在模型中,你可以使用belongsToMany方法来定义关系。

class Category extends Model
{
public function customers()
{
return $this->belongsToMany(Customer::class, 'databaseB.category_customer', 'category_id', 'customer_id');
}
}
class Customer extends Model
{
public function categories()
{
return $this->belongsToMany(Category::class, 'databaseB.category_customer', 'customer_id', 'category_id');
}
}

最新更新