I've been leaning Laravel and trying to implement something and I did, it worked but I heard that it might be possible to do the same in an easier way using Eager Loading.
Imagine that we have 4 tables: garages
, cars
, securities
, places
.
garages
is where you can find the cars
, securities
is the security that is keeping that car safe inside of a garage, and places
is where you can find garages similar to that one.
What I want is to list garages
and join the three tables that is cars
, securities
and places
like this:
Garage 1 has 2 cars with 3 securities and has 3 more garages similar
Garage 2 has 1 cars with 1 securities and has 2 more garages similar
And here is the query:
select
g.garage_name,
count(distinct c.car_id) as count_cars,
count(distinct s.security_id) as count_securities,
count(distinct p.place_id) as count_places
from garages g
left join cars c on c.garage_id = g.garage_id
left join securities s on s.car_id = c.car_id
left join places p on p.garage_id = g.garage_id
group by g.garage_name
order by g.garage_name;
It's working, as you can see here.
I converted it to:
$garages = Garages::select('garage_name',
DB::raw('count(distinct cars.car_id) as count_cars'),
DB::raw('count(distinct securities.security_id) as count_securities'),
DB::raw('count(distinct places.place_id) as count_places'))
->leftJoin('cars', 'cars.garage_id', '=', 'garages.garage_id')
->leftJoin('securities', 'securities.car_id', '=', 'cars.car_id')
->leftJoin('places', 'places.garage_id', '=', 'garages.garage.id')
->groupBy('garages.garage_name')
->orderBy('garages.garage_name')
->get();
As I said above, it's working but I'm wondering if there's an easier way for doing this using Eager Loading and how to convert?
- When I say easier I mean more readable, separated, the right way instead of that big query.