两个外键,如何用laravel eloquent映射
我在 MySQL 中有两个表,其中第一个称为用户,第二个称为游戏.表结构如下.
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.
用户
- id(主要)
- 电子邮件
- 密码
- 真实姓名
游戏
- id(主要)
- user_one_id(国外)
- user_one_score
- user_two_id(国外)
- user_two_score
我的游戏桌有两个对外关系,两个用户.
My games table is holding two foreign relations to two users.
我的问题是如何为这个表结构建立模型关系??- 根据 laravel 文档,我应该在模型内部创建一个函数并将其与其关系绑定
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
例如
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.
谢谢
推荐答案
迁移:
$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');
还有一个模型:
public function player1()
{
$this->belongsTo('Game', 'player1');
}
public function player2()
{
$this->belongsTo('Game', 'player2');
}
编辑按照用户 deczo 的建议将游戏"更改为游戏".
EDIT changed 'game' to 'Game' as user deczo suggested.
相关文章