hardevine / LaravelShoppingcart

A simple shopping cart implementation for Laravel
MIT License
348 stars 120 forks source link

Eager loading #34

Closed nurmuhammet-ali closed 3 years ago

nurmuhammet-ali commented 3 years ago

Hello, I cannot realize why carts are not eager loading relationships of model when cart instance accessed by model, example:

@foreach($carts as $cart)
    {{ $cart->model->brand->name }}
    {{ $cart->model->media->getImage('img') }}
   {{-- ... --}}
@endforeach

And here queries,

select * from `products` where `products`.`id` = 2 limit 1
select * from `media` where `media`.`model_id` in (2) and `media`.`model_type` = 'App\Models\Product'
select * from `brands` where `brands`.`id` in (9)

select * from `products` where `products`.`id` = 1 limit 1
select * from `media` where `media`.`model_id` in (1) and `media`.`model_type` = 'App\Models\Product'
select * from `brands` where `brands`.`id` in (5) 

As you see, instead of making 2 query for brands and media, it should do one. Like this:

select * from `brands` where `brands`.`id` in (5, 9) 
select * from `media` where `media`.`model_id` in (1, 2) and `media`.`model_type` = 'App\Models\Product'

Please help, imagine having lot of relationships and lot of records. This is very bad practice. And it should be fixed as fast as possible.

nurmuhammet-ali commented 3 years ago

Is there anybody here?

hardevine commented 3 years ago

how about https://laravel.com/docs/8.x/eloquent-relationships#lazy-eager-loading