To achieve this, you can define two separate many-to-many relationships in your Work model, each using a different pivot table. You'll need two pivot tables: one for authors and one for publishers. Here's how you can set it up:
-
Create the Pivot Tables:
You'll need two pivot tables, for example,
account_work_authorsandaccount_work_publishers. You can create these using migrations:// Migration for account_work_authors Schema::create('account_work_authors', function (Blueprint $table) { $table->id(); $table->foreignId('work_id')->constrained()->onDelete('cascade'); $table->foreignId('account_id')->constrained()->onDelete('cascade'); $table->timestamps(); }); // Migration for account_work_publishers Schema::create('account_work_publishers', function (Blueprint $table) { $table->id(); $table->foreignId('work_id')->constrained()->onDelete('cascade'); $table->foreignId('account_id')->constrained()->onDelete('cascade'); $table->timestamps(); }); -
Define Relationships in the
WorkModel:In your
Workmodel, define the relationships using thebelongsToManymethod, specifying the pivot table for each relationship.class Work extends Model { public function authors() { return $this->belongsToMany(Account::class, 'account_work_authors'); } public function publishers() { return $this->belongsToMany(Account::class, 'account_work_publishers'); } } -
Define Relationships in the
AccountModel:Similarly, you can define inverse relationships in the
Accountmodel if needed.class Account extends Model { public function authoredWorks() { return $this->belongsToMany(Work::class, 'account_work_authors'); } public function publishedWorks() { return $this->belongsToMany(Work::class, 'account_work_publishers'); } } -
Usage:
You can now access the authors and publishers of a work like this:
$work = Work::find(1); // Get authors $authors = $work->authors; // Get publishers $publishers = $work->publishers;
This setup allows you to maintain two distinct many-to-many relationships between the Work and Account models, one for authors and another for publishers.