[英]Laravel Eloquent Eager Loading with belongsToMany too slow
I have users
that can belong to groups
in a many to many relationship. 我有
users
可以属于groups
在多对多的关系。 I'm trying to retrieve ( paginate ) users with all the groups they belong to. 我试图检索与他们所属的所有组(PAGINATE)的用户。 This works fine, but when I have 1000+ users, things get really slow, even though I'm only paginating 25 to 50 at a time.
效果很好,但是当我有1000多个用户时,即使我一次只分页25到50,事情也会变慢。 On my User model:
在我的用户模型上:
public function groups()
{
return $this->belongsToMany('App\Models\UserGroup', 'group_user', 'user_id', 'group_id');
}
My query is: 我的查询是:
User::with('groups')->paginate(50);
So if I have around 50 users total in the database (MySQL), everything is super fast (<= 300ms). 因此,如果我在数据库(MySQL)中总共有大约50个用户,则一切都非常快(<= 300ms)。 But when I add 1000, even though I'm still only paginating up to 50 per page, it crawls (~3 seconds).
但是,当我添加1000时,即使我仍然只对每页最多分页50,它也会爬行(约3秒)。
Actually normal request with around 50 TOTAL users is ~100ms, not 300ms. 实际上,大约50个TOTAL用户的正常请求是100ms,而不是300ms。
Thanks to Thiago Barcala's comment, I was able to analyze the query logs with: 感谢Thiago Barcala的评论,我能够使用以下命令分析查询日志:
\DB::enableQueryLog();
// perform query...
var_dump(\DB::getQueryLog());
And I found the issue. 我发现了问题。 Basically, I had a
with
attribute on my groups model: 基本上,我的分组模型上有一个
with
属性:
protected $with = [
'features',
'users'
];
So I have a bunch of users being returned, and they're getting their groups returned, and each of those groups are returning all of the users in them. 因此,我有一堆用户被返回,他们正在返回其组,而这些组中的每个组都在返回它们中的所有用户。 So I was getting like 10MB worth of data returned all because of this relation including more relations.
因此,由于这种关系(包括更多的关系),我获得了价值10MB的数据返回。 I removed the
with
and all is well. 我删除了
with
,一切都很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.