Laravel Eloquent - 如何使用 ORM 向远距离相关模型添加 Where 条件?
Laravel Eloquent - How Do You Add a Where Condition to a Distantly Related Model Using the ORM?
我目前有:
Cars::with('cases')->with(['parts', 'parts.engines', 'parts.engines.metals'])
->orderBy('car_name', 'DESC')->orderBy('id', 'DESC');
上面将列出我的 cars
table 中的所有行以及与每辆汽车的发动机相关的金属。 metals
table 通过 parts
与 cars
table 相关,然后是 engines
table。
我试过使用:
Cars::with('cases')->whereHas(['parts', 'parts.engines', 'parts.engines.metals'], function($query){
$query->where('weight', '=', 45)
})->orderBy('car_name', 'DESC')->orderBy('id', 'DESC');
但是由于 whereHas()
的第一个参数不接受数组而且我看不到 link 与它建立远距离关系的方法。
如何使用内置 ORM 在 metals
table 中的列上应用 WHERE 条件?
我想你是这个意思:
Cars::with(['cases', 'parts', 'parts.engines', 'parts.engines.metals' => function($query){
$query->where('weight', '=', 45);
}])->orderBy('car_name', 'DESC')->orderBy('id', 'DESC');
whereHas()
只需要您要为其添加条件的关系的名称。因此,如果您尝试向金属添加条件,则只需限制 parts.engines.metals
关系。
附带说明一下,当您急切加载嵌套关系时,您不需要同时指定加载中间关系。也就是说,当你预先加载 parts.engines
时,你不需要同时预先加载 parts
.
因此,您的查询类似于:
Cars::with(['cases', 'parts.engines.metals'])
->whereHas('parts.engines.metals', function($query) {
$query->where('weight', '=', 45)
})
->orderBy('car_name', 'DESC')
->orderBy('id', 'DESC');
此查询将仅检索具有重量为 45 的相关金属的汽车。此外,对于检索到的那些汽车,它还会预先加载与这些相关的所有外壳、零件、发动机和金属汽车。
我目前有:
Cars::with('cases')->with(['parts', 'parts.engines', 'parts.engines.metals'])
->orderBy('car_name', 'DESC')->orderBy('id', 'DESC');
上面将列出我的 cars
table 中的所有行以及与每辆汽车的发动机相关的金属。 metals
table 通过 parts
与 cars
table 相关,然后是 engines
table。
我试过使用:
Cars::with('cases')->whereHas(['parts', 'parts.engines', 'parts.engines.metals'], function($query){
$query->where('weight', '=', 45)
})->orderBy('car_name', 'DESC')->orderBy('id', 'DESC');
但是由于 whereHas()
的第一个参数不接受数组而且我看不到 link 与它建立远距离关系的方法。
如何使用内置 ORM 在 metals
table 中的列上应用 WHERE 条件?
我想你是这个意思:
Cars::with(['cases', 'parts', 'parts.engines', 'parts.engines.metals' => function($query){
$query->where('weight', '=', 45);
}])->orderBy('car_name', 'DESC')->orderBy('id', 'DESC');
whereHas()
只需要您要为其添加条件的关系的名称。因此,如果您尝试向金属添加条件,则只需限制 parts.engines.metals
关系。
附带说明一下,当您急切加载嵌套关系时,您不需要同时指定加载中间关系。也就是说,当你预先加载 parts.engines
时,你不需要同时预先加载 parts
.
因此,您的查询类似于:
Cars::with(['cases', 'parts.engines.metals'])
->whereHas('parts.engines.metals', function($query) {
$query->where('weight', '=', 45)
})
->orderBy('car_name', 'DESC')
->orderBy('id', 'DESC');
此查询将仅检索具有重量为 45 的相关金属的汽车。此外,对于检索到的那些汽车,它还会预先加载与这些相关的所有外壳、零件、发动机和金属汽车。