如果未加载关系则阻止数据库查询

时间:2019-05-28 14:25:55

标签: laravel laravel-5

我有2个模型,例如CountryCity,它们之间的关系为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

2 个答案:

答案 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)

感谢

https://laracasts.com/discuss/channels/laravel/how-to-check-if-an-relationship-has-been-eager-loaded-or-not

就我而言

//...
if ($city->relationLoaded('country')) {
    dump($city->country);
} else {
    dump(null);
}
//...