Riz*_*yid 0 relationship laravel eloquent
假设我有三个与外键链接的数据库,即玩家,信用和照片。
player
id | name | address
credit
id | player_id | credit_status
photo
id | player_id
Run Code Online (Sandbox Code Playgroud)
假设我想获得所有具有credit_status $ status的玩家,我会这样做:
$status = 'bar';
Player::with('photo','credit')->whereHas('credit', function ($q) use ($status) {
$q->where('credit_status', $status)->with('credit_status');
})->paginate(15);
Run Code Online (Sandbox Code Playgroud)
这将列出所有具有credit_status $ credit的玩家,但仍然列出该玩家的所有积分,而不管其状态如何。
输出类似于:
{
id: 1
name: Andrew
address: home
photo: {
id: 2
photo: image1
}
credit: {
[
{
id: 6
credit_status: foo,
id: 2
credit_status: bar
}
]
}
},
{
id: 2
name: Mark
address: home
photo: {
id: 5
photo: image4
}
credit: {
[
{
id: 10
credit_status: foo,
id: 6
credit_status: bar,
id: 8
credit_status: bar
}
]
}
}
Run Code Online (Sandbox Code Playgroud)
我也想用('credit')过滤信用。我想要的输出:
{
id: 1
name: Andrew
address: home
photo: {
id: 2
photo: image1
}
credit: {
[
{
id: 2
credit_status: bar
}
]
}
},
{
id: 2
name: Mark
address: home
photo: {
id: 5
photo: image4
}
credit: {
[
{
id: 6
credit_status: bar,
id: 8
credit_status: bar
}
]
}
}
Run Code Online (Sandbox Code Playgroud)
您可以对with(限制急切加载)执行相同的过滤:
$creditFilter = function ($q) use ($status) {
$q->where('credit_status', $status);
};
Player::with(['photo', 'credit' => $creditFilter])
->whereHas('credit', $creditFilter)
->paginate(15);
Run Code Online (Sandbox Code Playgroud)
您可以保存该闭包并将其传递给with,whereHas因此不必两次键入相同的闭包。
Laravel 5.6文档-雄辩-关系-渴望加载-限制渴望加载