Laravel雄辩计数关系 [英] Laravel eloquent counting a relation
问题描述
所以如果我想要获得所有用户的所有位置,我只想这样做:
Location :: with(users) - > get();
但我也想知道每个位置有多少用户,尝试这样做
Location :: with(users) - > count(users) - > get );
但这没有用。
如果您使用热心加载,则不会出现提及的n + 1个问题。
$ locations = Location :: with('users') - > get();
$ locations-> users() - > count();
无论您有多少用户或位置,都应该产生三个查询。
- 根据位置模型计数查询
- 从位置选择*
- 从
中的用户选择*来自这一点也可以产生混淆:
$ locations = Location :: all();
$ locations-> users() - > count();
但是在这种情况下,它会为每个位置查询一次。
查看文档了解更多信息:
http:// laravel .com / docs / eloquent#eager-loading
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.
- 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
这篇关于Laravel雄辩计数关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!