php Laravel 雄辩的计数关系
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13197692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel eloquent counting a relation
提问by Arcade
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.
我是 laravel 和 eloquent 的新手,我不确定这是否可能。但我有 2 张表具有一对多的关系。一种是“位置”,一种是“用户”。一个位置可以有多个用户。
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 eachlocation has, I tried doing this
但我也想知道每个位置有多少用户,我试过这样做
Location::with("users")->count("users")->get();
But that didn't work.
但这没有用。
回答by ben at colourmill
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
- 针对位置模型的计数查询
- 从位置选择 *
- 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
回答by Bogdan
You should be using just withCountbut I guess it wasn't available back in 2012.
您应该使用 justwithCount但我想它在 2012 年不可用。
So here's how it should look like:
所以它应该是这样的:
Location::with("users")->withCount("users")->get();
And you will have an users_countattribute 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(向下滚动一点,您将看到Counting Related Models)
回答by iTech
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
这应该可以解决您的问题并为您提供每个位置的用户数量。您可以在循环中添加检查以忽略用户计数 = 0 的位置

