Laravel follow 如何减少 queries ?
overtrue 的包我在用的有4个,非常值得尊敬的开发者!言归正传。
需求和问题
目前有 模型 Comment
和 POST
,一篇文章有多个评论,每个评论都有一个 Upvote
,进行投票。不知道大家有没有注意到,每增加一个评论,laravel follow 都会增加一个query,类似如下的语句:
select exists(select * from `users` inner join `followables` on `users`.`id` = `followables`.`user_id` where `followables`.`followable_id` = '255' and `followables`.`followable_type` = 'App\Models\Post' and `followables`.`relation` in ('upvote', 'downvote') and `user_id` = '1') as `exists`
类似解决方案
在大名鼎鼎的laracast的视频中,我发现 lets build a forum with laravel
这部教程中第20章 20-From 56 Queries Down to 2
也讲到降低的方法。大概步骤如下:
在 comment
加入类似 $protected $with = ['user'] ?此处不知道何意。
把:
return $this->favorites()->where('user_id',auth()->id())->exists();
修改为:
return !!$this->favorites->where('user_id',auth()->id())->count();
视频经过测试,随着评论的增加,queries并没有增加。
改进方案
英文水平有限,听得七分水平,不知道如何修改,请大神改进,多谢。
推荐文章: