【问题标题】:Laravel relationship to show all posts by authors that they followLaravel 关系显示他们关注的作者的所有帖子
【发布时间】:2016-04-03 09:58:02
【问题描述】:

通常可以弄清楚这些关系,但很难理解这一点。

我有一个基本的博客平台,允许用户注册和发布博客文章。

用户也可以关注其他用户。

我正在尝试创建一个可以看到我关注的作者的所有博客文章的视图

我有一个普通的用户表,然后是一个包含创建者的 user_id 的博客帖子表。

对于追随者,我有一个名为追随者的数据透视表,其中包含 user_id 和 follower_id。

这是我获取所有帖子的基本路线:

$posts = Post::orderBy('created_at', 'DESC')->get();

如何更改它,使其仅显示帖子 user_id 是在关注者表中匹配的字段的帖子?

谢谢。

【问题讨论】:

    标签: php laravel-5


    【解决方案1】:

    你可以试试这样的:

    应用\用户模型:

    public function favoriteAuthors()
    {
        return $this->belongsToMany(
            User::class, // as Author
            'followers', // pivot table
            'follower_id', // as follower_id
            'user_id', // as author_id
        );
    }
    
    public function posts()
    {
        return $this
        ->hasMany(Post::class, 'user_id', 'id')
        ->orderBy('created_at', 'DESC');
    }
    

    然后加载您最喜欢的作者的所有帖子:

    $posts = User::with('favoriteAuthors.posts')->find(auth()->user()->id);
    

    你也可以使用这样的东西:

    if($me = auth()->user()) {
    
        $me->load(['favoriteAuthors.posts']);
    }
    

    现在$me 将包含您关注的用户,每个用户都将包含他们的帖子。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-23
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 2019-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多