mardi 28 mai 2019

Prevent DB query if relation was not loaded

I have 2 models, for example, Country and City with relations one-to-many.

When I run this code

$countries = Country::query()->with('cities')->get();

foreach ($countries as $country) {
    $cities = $country->cities;

    foreach ($cities as $city) {
        dump($city->country);
    }
}

, on the each $city->country call I have a query to DB

select * from `countries` where `countries`.`id` = ? limit 1 

If relation (in my case cities.country) was not loaded with eager loading, is there a possibility to prevent making DB query on the each $city->county call?

Instead getting the null, for example.



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2QqMZPK
via IFTTT

Aucun commentaire:

Enregistrer un commentaire