I'm new to laravel and eloquent and I'm not sure if this is even possible. but I have 2 tables with a one to many relationship. One is "locations" and one is "users". One location can have many users.
So if I wanted to get all locations with all users I would just do this:
Location::with("users")->get();
But I also want to know how many users each location has, I tried doing this
Location::with("users")->count("users")->get();
But that didn't work.
The n+1 issue that was mentioned doesn't occur if you use eager loading.
$locations = Location::with('users')->get(); $locations->users()->count();
This should result in three queries, no matter how many users or locations you have.
The confusion arises from the fact that this also works:
$locations = Location::all(); $locations->users()->count();
But in this case, it does query once for each location.
See the docs for more info: http://laravel.com/docs/eloquent#eager-loading
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With