简体   繁体   中英

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

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.

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM