Laravel follow 如何减少 queries ?

overtrue 的包我在用的有4个,非常值得尊敬的开发者!言归正传。

需求和问题

目前有 模型 CommentPOST ,一篇文章有多个评论,每个评论都有一个 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并没有增加。

改进方案

英文水平有限,听得七分水平,不知道如何修改,请大神改进,多谢。

《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 1

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!