两个外键,如何映射与laravel雄辩 [英] two foreign keys, how to map with laravel eloquent
问题描述
用户
- id(primary)
- 电子邮件
- 密码
- real_name
游戏
- id(Primary)
- user_one_id(foreign)
- user_one_score
- user_two_id(foreign)
- user_two_score
我的游戏表与两个用户持有两个外交关系。
我的问题是我如何使这个表结构的模型关系? - 根据 Laravel文档,我应该在模型内部建立一个函数,并将其与它的关系绑定
例如
public function users()
{
$这 - >属于关联( '游戏');
}
然而,在文档中似乎找不到任何东西,告诉我如何处理两个外键。像我上面的表结构一样。
我希望你可以帮助我。
谢谢
迁移:
$表 - >整数( 'PLAYER1') - >无符号();
$ table-> foreign('player1') - > references('id') - > on('users') - > onDelete('cascade');
$ table-> integer('player2') - > unsigned();
$ table-> foreign('player2') - > references('id') - > on('users') - > onDelete('cascade');
和一个模型:
public function player1()
{
$ this-> belongsTo('Game','player1');
}
public function player2()
{
$ this-> belongsTo('Game','player2');
}
编辑
更改游戏以用户分解建议为游戏。
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)
- 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.
这篇关于两个外键,如何映射与laravel雄辩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!