Skip to content
Advertisement

two foreign keys, how to map with laravel eloquent

I have two tables in MySQL, where the first one is called users and the second one is called games. The table structure is as follows.

users

  • id (primary)
  • email
  • password
  • real_name

games

  • id (Primary)
  • user_one_id (foreign)
  • user_one_score
  • user_two_id (foreign)
  • user_two_score

My games table is holding two foreign relations to two users.

My question is how do I make the model relations for this table structure?? – According to the laravel documentation, I should make a function inside the model and bind it with its relations

for instance

public function users()
{
    $this->belongsTo('game');
}

however I can’t seem to find anything in the documentation telling me how to deal with two foreign keys. like in my table structure above.

I hope you can help me along the way here.

Thank you

Advertisement

Answer

A migration:

$table->integer('player1')->unsigned();
$table->foreign('player1')->references('id')->on('users')->onDelete('cascade');
$table->integer('player2')->unsigned();
$table->foreign('player2')->references('id')->on('users')->onDelete('cascade');

And a Model:

public function player1()
{
    $this->belongsTo('Game', 'player1');
}
public function player2()
{
    $this->belongsTo('Game', 'player2');
}

EDIT changed ‘game’ to ‘Game’ as user deczo suggested.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement