Laravel雄辩计数关系 [英] Laravel eloquent counting a relation

查看:93
本文介绍了Laravel雄辩计数关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的laravel和雄辩,我不知道这是否可能。但我有2个表与一对多的关系。一个是位置,一个是用户。一个位置可以有很多用户。



所以如果我想要获得所有用户的所有位置,我只想这样做:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆