I have two MySQL schemas like this:
Database A containing "categories" Database B containing "customers"
Now, I need to create a pivot relationship between them, so "category_customer" is inserted into Database B. Can I use the classic pivot form to create the relationship? Then add the foreign key that points to Database A?
Thank you very much.
CodePudding user response:
create the pivot table "category_customer" in Database B and add the foreign key that points to the "categories" table in Database 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');
});
in the Model you can use the belongsToMany method to define the relationship.
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');
}
}