【问题标题】:How to get posts of people I am following in Eloquent如何在 Eloquent 中获取我关注的人的帖子
【发布时间】:2016-09-01 21:52:32
【问题描述】:

我有一个User 模型,一个Post 模型。

在我的User 模型中,我有以下内容:

public function followers()
{
    return $this->belongsToMany(User::class, 'followers', 'follower_id', 'user_id')->withTimestamps();
}


public function following()
{
    return $this->belongsToMany(User::class, 'followers', 'user_id', 'follower_id')->withTimestamps();
}


public function posts()
{
    return $this->hasMany(Post::class);
}

所以基本上,$user->following 为我提供了我关注的用户集合,$user->posts 为我提供了帖子集合。我想这样做:

$posts = [];
$user->following->each(function($f) use($posts) {
   $posts[] = $f->posts;
});

但更雄辩的方式,如果这是有道理的。因为我想在此之后对结果进行分页。我正在考虑做hasManyThrough,但不知道怎么做?

【问题讨论】:

  • 一个用户会有很多帖子,一个用户会有很多关注者。但是我无法通过“关注者”看到用户和帖子之间的关系。

标签: laravel eloquent


【解决方案1】:

Here 链接到带有答案的类似问题。

我认为你想做这样的事情:

User::where('id', $id)->with(['following.posts' => function ($q) use (&$posts) {
    $posts= $q->get()->unique();
}])->first();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-13
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 2015-04-23
    • 1970-01-01
    • 1970-01-01
    • 2012-03-10
    相关资源
    最近更新 更多