Get the followers on a post efficient way in larav

2019-07-19 12:08发布

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.

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).

Post Model

/**
 * 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');
}

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.

I am returning a paginated list of 20 posts per page from API as json.

Update

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
},

and its giving me

followers: [
{
    user_id: 32
},
{
    user_id: 3
},
{
    user_id: 21
},
{
    user_id: 33
},
{
    user_id: 46
},
{
    user_id: 30
}

]

I want something like

followers : [45,2,45,87,12] //as array of ids

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

Other Option

One another way will be to cache number of followers on posts table like followers_countand 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.

Please help guys, how twitter, facebook has done it? to get the followers on a post and is current user following given post.

1条回答
迷人小祖宗
2楼-- · 2019-07-19 12:32

You may use something like array_reduce after you get followers.

Example:

$followers = array_reduce($post->followers, function ($c, $i) {
    $c[] = $i->user_id;
}, []);

Now the $followers contain all follower ids.

查看更多
登录 后发表回答