Dunebook / codesource

0 stars 0 forks source link

laravel-eloquent-relationships-explained/ #22

Open utterances-bot opened 2 years ago

utterances-bot commented 2 years ago

Laravel eloquent relationships explained

Eloquent ORM is one of the most exciting and powerful built-in features in Laravel. Before we start we’ve to understand, what ORM means. ORM means object relational mapper. It handles database operations by representing data as objects.

https://codesource.io/laravel-eloquent-relationships-explained/

chrischi1989 commented 2 years ago

Don't do this:

Assuming you have a collection of 1000 $model instances and each $model has one ->relation, you'll cause 1000 additional queries triggered from the view because $model->relation is lazy-loaded whenever the view is rendered.

@foreach($models as $model)
{{ $model->relation->property }}
@endforeach

Correct way:

Eager-load your relationships with the built-in Model::with() method before (!!!) you display them. This will only cause:

1 query to load all the models 1 additional query with a well formed WHERE id IN(...) condition

$models = Model::with('relation')->get()
@foreach($models as $model)
{{ $model->relation->property }}
@endforeach