two foreign keys, how to map with laravel eloquent

二次信任 提交于 2019-12-30 06:10:08

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/25061687/two-foreign-keys-how-to-map-with-laravel-eloquent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!