[英]Adding multiple relations in eager loading
My application: In my application users have the possibility to predict the scores of upcoming soccer games. 我的应用程序:在我的应用程序中,用户可以预测即将到来的足球比赛的得分。 So basically there is a relationship between the
user
and predictions
, but there is also a relationship between the prediction
and my Match model
. 因此,基本上,
user
与predictions
之间存在关系,但是prediction
与我的Match model
之间也存在关系。 Currently I add the homeTeamName
& awayTeamName
in my prediction table but this is not really necessary since I store my match_id
in my predictions table. 当前,我在预测表中添加了
homeTeamName
和awayTeamName
,但这并不是必需的,因为我将match_id
存储在预测表中。 I want to load my team names from my match table
based on the match_id
from my prediction table instead of adding the names in the predictions table. 我想根据我的预测表中的
match_id
从我的match table
加载球队名称,而不是在预测表中添加球队名称。
Here is a look at my relations: 看一下我的关系:
Match model 匹配模型
class Match extends Model
{
public function Predictions() {
return $this->hasMany('App\Prediction'); // one match has many predictions
}
}
Prediction model 预测模型
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
}
}
User model 用户模型
class User extends Authenticatable
{
public function Predictions() {
return $this->hasMany('App\Prediction'); // a user has many predictions
}
}
Using lazy eager loading for this query 对这个查询使用延迟加载
public function showPredictions() {
\DB::enableQueryLog();
$user = Auth::user();
$user->load('predictions', 'predictions.match');
dd(\DB::getQueryLog());
return view('predictions', compact('user'));
}
output 输出
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');
Try this 尝试这个
$user->load([
'predictions.match' => function ($query) {
$query->where('status', 'SCHEDULED');
}
]);
Or if you have status
column in both tables: 或者,如果两个表中都有“
status
列:
$user->load([
'predictions.match' => function ($query) {
$query->where('predictions.status', 'SCHEDULED');
}
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.