laravel 两个外键,如何用laravel eloquent映射

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25061687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:53:14  来源:igfitidea点击:

two foreign keys, how to map with laravel eloquent

phpmysqlsqllaraveleloquent

提问by Rohwedder

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.

我在 MySQL 中有两个表,其中第一个称为用户,第二个称为游戏。表结构如下。

users

用户

  • id (primary)
  • email
  • password
  • real_name
  • id(主要)
  • 电子邮件
  • 密码
  • 真正的名字

games

游戏

  • id (Primary)
  • user_one_id (foreign)
  • user_one_score
  • user_two_id (foreign)
  • user_two_score
  • id(主要)
  • user_one_id(国外)
  • user_one_score
  • user_two_id(国外)
  • 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

我的问题是如何为这个表结构建立模型关系?-根据laravel文档,我应该在模型内部创建一个函数并将其与其关系绑定

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

谢谢

回答by peter.babic

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');
}

EDITchanged 'game' to 'Game' as user deczo suggested.

按照用户 deczo 的建议,编辑将“游戏”更改为“游戏”。

回答by drmarvelous

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.

不幸的是,您进行此设置的方式不太可能在当前上下文中起作用。您可能更喜欢使用belongsTo 方法,但同样只支持一种关系。

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

你可以实现一个user1()belongsTo,一个user2()belongsTo,最后只声明一个非雄辩的函数来返回两者(类似于$users = array($this->user1(), $this->user2())