我有2个模型,例如Country
和City
,它们之间的关系为one-to-many
。
当我运行这段代码
$countries = Country::query()->with('cities')->get();
foreach ($countries as $country) {
$cities = $country->cities;
foreach ($cities as $city) {
dump($city->country);
}
}
,在每个$city->country
调用中,我都有一个查询到数据库
select * from `countries` where `countries`.`id` = ? limit 1
如果没有立即加载关系(在我的情况下为cities.country
),是否有可能防止在每个$city->county
调用中进行数据库查询?
我不需要$country
变量。如果在主查询中未加载关系null
,则需要获取cities.country
。
答案 0 :(得分:2)
为什么不做逆运算:
$cities = City::with('country')->get();
// this way you would loop only once:
foreach ($cities as $city) {
dump($city->country);
}
然后使用您的方法:
foreach ($countries as $country) {
$cities = $country->cities;
foreach ($cities as $city) {
dump($country);
// here the $country variable
// is the same as the $city->country one, so no need to query it again..
}
}
答案 1 :(得分:-1)
感谢
就我而言
//...
if ($city->relationLoaded('country')) {
dump($city->country);
} else {
dump(null);
}
//...