Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vincent15000's avatar

Many to many to many relationship ?

Hello,

I have a question about a many to many to many relationship.

I successfully use the many to many relationship. But I have an example that's more difficult to do.

I have three tables : games, designers, roles.

A designer has one or more roles : author, illustrator, ... A game has on or more designers and for each designer, one or more roles.

This could be like this in the relation table 'game_designer_role' :

  • game_id
  • designer_id
  • role_id

The three fields have to be unique together.

But how is it possible to declare this, for example with belongsToMany() ? I have seen a pivot table, but is it really recommanded to use one ?

Otherwise I can also do like this :

game_designer

  • id
  • game_id
  • designer_id

game_designer_role

  • game_designer_id
  • role_id

Is there a better way to manage these multiple relationships ?

Thanks a lot.

Vincent

0 likes
2 replies
bobbybouwmann's avatar
Level 88

You can use an extra column in the pivot table to set the role_id between the game and the designer. However, it's not possible to set this up as a real relationship between game and role or designer and role. You can create a pivot model and add the relationship in there.

class DesignGame extends Pivot
{
    protected $table = 'design_game';

    public function role()
    {
        $this->belongsTo(Role::class);
    }
}

Then in your code, you can do this:

$game = Game::with('designers')->find(1);

$game->designers->first()->pivot->role;

This should put you in the right direction

Finally, you can add a unique constraint on all three columns to make sure they are always unique.

Schema::table('design_game', function (Blueprint $table) {
    $table->foreignId('game_id')->references('id')->on('games');
    $table->foreignId('designer_id')->references('id')->on('designers');
    $table->foreignId('role_id')->references('id')->on('roles');

    $table->unique(['game_id', 'designer_id', 'role_id']);
});

Note that the above code is the new Laravel 7 syntax for creating a column including foreign keys in migrations.

Please or to participate in this conversation.