[英]Adding multiple relations in eager loading
我的應用程序:在我的應用程序中,用戶可以預測即將到來的足球比賽的得分。 因此,基本上, user
與predictions
之間存在關系,但是prediction
與我的Match model
之間也存在關系。 當前,我在預測表中添加了homeTeamName
和awayTeamName
,但這並不是必需的,因為我將match_id
存儲在預測表中。 我想根據我的預測表中的match_id
從我的match table
加載球隊名稱,而不是在預測表中添加球隊名稱。
看一下我的關系:
匹配模型
class Match extends Model
{
public function Predictions() {
return $this->hasMany('App\Prediction'); // one match has many predictions
}
}
預測模型
class Prediction extends Model
{
public function User() {
return $this->belongsTo('App\User'); // prediction belongs to a user
}
public function Match() {
return $this->belongsTo('App\Match', 'match_id', 'match_id'); // prediction belongs to a match
}
}
用戶模型
class User extends Authenticatable
{
public function Predictions() {
return $this->hasMany('App\Prediction'); // a user has many predictions
}
}
對這個查詢使用延遲加載
public function showPredictions() {
\DB::enableQueryLog();
$user = Auth::user();
$user->load('predictions', 'predictions.match');
dd(\DB::getQueryLog());
return view('predictions', compact('user'));
}
輸出
array:3 [▼
0 => array:3 [▼
"query" => "select * from `users` where `id` = ? limit 1"
"bindings" => array:1 [▼
0 => 1
]
"time" => 13.0
]
1 => array:3 [▼
"query" => "select * from `predictions` where `predictions`.`user_id` in (?)"
"bindings" => array:1 [▼
0 => 1
]
"time" => 1.0
]
2 => array:3 [▼
"query" => "select * from `matches` where `matches`.`id` in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
"bindings" => array:10 [▼
0 => 233133
1 => 233134
2 => 233135
3 => 233136
4 => 233137
5 => 233138
6 => 233139
7 => 233140
8 => 233141
9 => 233142
]
"time" => 1.0
]
]
為了渴望加載嵌套關系,可以使用“點”語法
$user->load('predictions', 'predictions.match')->where('status', 'SCHEDULED');
嘗試這個
$user->load([
'predictions.match' => function ($query) {
$query->where('status', 'SCHEDULED');
}
]);
或者,如果兩個表中都有“ status
列:
$user->load([
'predictions.match' => function ($query) {
$query->where('predictions.status', 'SCHEDULED');
}
]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.