问题描述
我已经使用Eloquent for API构建了一个关注者系统(感谢),但是查询(n+1)
的速度非常慢,它需要5秒钟的响应时间,是我的操作方式.
I have build a follower system using Eloquent for API (thanks to John Bupit ) but I am getting very slow query (n+1)
, its taking 5 second for response, here is the way I have done it.
我需要知道当前帖子之后的当前用户,所以我在所有帖子后都添加了所有用户的id
(这使得很多sql查询).
I need to know is current user following current post, so I have appended the id
of all users following on every post (which is making a lot of sql queries).
发布模型
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $appends = ['followers'];
/**
* Get the list of followers of this post.
*
* @return bool
*/
public function getFollowersAttribute()
{
return $this->followers()->get()->lists('id');
}
如您所见,我在模型上添加了一个属性followers
,该属性用于获取ids
用户关注的列表.
As you can see I have added an attribute followers
on model which fetches the lists of ids
user following.
还有什么其他方法可以让用户获得以下发布状态,如何使其更快.
Is there any other way I can get the following state of post for user, How can I make it faster.
如果用户关注该帖子且关注者总数,我想显示关注.
I want to show Following if user is following the post with a count of total followers.
我从api返回每页20个帖子的分页列表,作为json.
I am returning a paginated list of 20 posts per page from API as json.
更新
我现在尝试过快速加载并快速加载,但是如何仅获取用户ID列表,而不获取漏洞用户模型.这是我的代码
I have tried eager loading and its fast now, but how can I get only the list of user ids, not hole user model. here is my code
$post->with([
'followers' => function($q) {
$q->select('user_id'); // select id is giving Column 'id' in field list is ambiguous
},
及其给了我
followers: [
{
user_id: 32
},
{
user_id: 3
},
{
user_id: 21
},
{
user_id: 33
},
{
user_id: 46
},
{
user_id: 30
}
]
我想要
followers : [45,2,45,87,12] //as array of ids
这会引起问题,例如,如果某个帖子获得1000个关注者,我敢打赌它会再次变慢,并且我不能限制eager loaded
结果
it will cause problem, for example if a post get 1000 follower, I bet it will be slow again, and I cant limit the eager loaded
result
$q->select('user_id')->limit(20); // Limit doesn't work
其他选项
另一种方法是在followers_count
之类的帖子表上缓存关注者的数量,然后我可以使用某种方式检查登录用户是否使用标志ex跟踪每个帖子. is_following
.我不知道我在这里迷路了.
One another way will be to cache number of followers on posts table like followers_count
and then some way I can check that logged in user is following the each post using a flag ex. is_following
. I dont know I am lost here.
请帮助大家,twitter,facebook是如何做到的?以便将关注者发布到帖子上,并且当前用户正在关注给定帖子.
推荐答案
您可以使用后,出现nofollow> array_reduce .
示例:
$followers = array_reduce($post->followers, function ($c, $i) {
$c[] = $i->user_id;
}, []);
现在$followers
包含所有关注者id
.
这篇关于在laravel 5.1中以高效的方式吸引关注者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!