【问题标题】:Get the followers on a post efficient way in laravel 5.1在 laravel 5.1 中以高效的方式获取关注者
【发布时间】:2015-11-21 05:02:35
【问题描述】:

我已经使用 Eloquent for API 构建了一个追随者系统(感谢 John Bupit),但我的查询速度非常慢 (n+1),响应时间为 5 秒,here 是我完成它的方式。

我需要知道当前用户是否关注当前帖子,所以我在每个帖子上附加了所有关注用户的id(这会进行大量的 sql 查询)。

后模型

/**
 * 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 用户关注的列表。

有没有其他方法可以让用户获得以下帖子状态,我怎样才能让它更快。

如果用户关注帖子的关注者总数,我想显示关注。

我正在从 API 以 json 形式返回每页 20 个帖子的分页列表。

更新

我已经尝试过急切加载并且现在速度很快,但是我怎样才能只获得用户 ID 列表,而不是孔用户模型。这是我的代码

$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 结果

$q->select('user_id')->limit(20); // Limit doesn't work

其他选项

另一种方法是在帖子表上缓存关注者的数量,例如followers_count,然后我可以通过某种方式检查登录用户是否使用标志 ex 关注每个帖子。 is_following。我不知道我在这里迷路了。

请大家帮忙,twitter、facebook 是怎么做到的?获取帖子的关注者并且当前用户关注给定的帖子。

【问题讨论】:

  • 您真的需要在$appends 中添加followers 吗?正如您所提到的,这将为您获取的每个用户查询数据库。您可以使用eager loading 来解决这个N + 1 查询问题。
  • 我想eager load,但是我怎样才能只获取id列表,它将返回每个用户模型,如果尝试说选择id,它会给出错误Column 'id' in field list is ambiguous跨度>

标签: php mysql laravel-5.1


【解决方案1】:

在获得followers 之后,您可以使用array_reduce 之类的东西。

例子:

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

现在$followers 包含所有关注者ids。

【讨论】:

    猜你喜欢
    • 2015-04-23
    • 1970-01-01
    • 2015-10-23
    • 2014-01-06
    • 2016-02-14
    • 2019-03-07
    • 2016-11-23
    • 1970-01-01
    • 2016-06-12
    相关资源
    最近更新 更多