Laravel eloquent counting a relation

php laravel eloquent

23591 просмотра

3 ответа

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:


But I also want to know how many users each location has, I tried doing this


But that didn't work.

Автор: Arcade Источник Размещён: 07.10.2019 08:58

Ответы (3)

36 плюса


The n+1 issue that was mentioned doesn't occur if you use eager loading.

$locations = Location::with('users')->get();


This should result in three queries, no matter how many users or locations you have.

  • count query against the location model
  • select * from locations
  • select * from users where in

The confusion arises from the fact that this also works:

$locations = Location::all();


But in this case, it does query once for each location.

See the docs for more info:

Автор: ben at colourmill Размещён: 15.05.2014 05:32

7 плюса

You need to call the count method on each Location record to get users count per location, here is an example:

foreach(Location::get() as $location) // or foreach(Location::with("users")->get() as $location)
  echo $location->users()->count();

This should solve your problem and give you the number of users per each location. You can add a check in the loop to ignore locations with users' count = 0

Автор: iTech Размещён: 13.11.2012 08:36

4 плюса

You should be using just withCount but I guess it wasn't available back in 2012.

So here's how it should look like:


And you will have an users_count attribute available on you object.

Read the docs for more details: (scroll down a bit and you'll see Counting Related Models)

Автор: Bogdan Размещён: 21.03.2018 12:42