简体   繁体   English

Laravel雄辩地计算了一种关系

[英]Laravel eloquent counting a relation

I'm new to laravel and eloquent and I'm not sure if this is even possible. 我是laravel和eloquent的新手,我不确定这是否可能。 but I have 2 tables with a one to many relationship. 但是我有2张桌子,有一对多的关系。 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. 如果您使用预先加载,则不会出现提及的n + 1问题。

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

$locations->users()->count();

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();

$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 有关详细信息,请参阅文档: http//laravel.com/docs/eloquent#eager-loading

You need to call the count method on each Location record to get users count per location, here is an example: 您需要在每个位置记录上调用count方法以获取每个位置的用户数,这是一个示例:

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 您可以在循环中添加一个检查以忽略用户count = 0的位置

You should be using just withCount but I guess it wasn't available back in 2012. 你应该只使用withCount但我想它在2012年才可用。

So here's how it should look like: 所以这是它应该是这样的:

Location::with("users")->withCount("users")->get();

And you will have an users_count attribute available on you object. 并且您将在对象上使用users_count属性。

Read the docs for more details: https://laravel.com/docs/5.5/eloquent-relationships#querying-relations (scroll down a bit and you'll see Counting Related Models ) 阅读文档以获取更多详细信息: https//laravel.com/docs/5.5/eloquent-relationships#querying-relations (向下滚动一下,您将看到计数相关模型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM