問題描述
我在 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.
這篇關于兩個外鍵,如何用laravel eloquent映射的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!