Martin Rohwedder
Martin Rohwedder

Reputation: 1751

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

games

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

Upvotes: 11

Views: 11477

Answers (2)

peter.babic
peter.babic

Reputation: 3374

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.

Upvotes: 15

drmarvelous
drmarvelous

Reputation: 1681

Unfortunately the way you have this setup is not likely to work in the current context. You may have more luck with the belongsTo method, but again that only supports one relationship.

You could implement a user1() belongsTo, a user2() belongsTo and finally just declare a non eloquent function to return both (something like $users = array($this->user1(), $this->user2())

Upvotes: 0

Related Questions