获取 Laravel 中关注者的帖子

5
我希望为已认证的用户显示一个动态页面,该页面显示他们关注的用户最新发布的帖子。我已经设置了一个关注系统,其中包括以下内容:
表格:
- 帖子 - 用户 - 关注
用户模型:
 public function follow() {  
    return $this->BelongsToMany( 'User', 'Follow' ,'follow_user', 'user_id');
}

Feed控制器:

public function feed () {

    $user = (Auth::user());

        return View::make('profile.feed')->with('user',$user);

    }

Feed.blade

  @foreach ($user->follow as $follow)

 @foreach ($follow->posts as $post)

     //* post data here.

  @endforeach

 @endforeach

这里正在获取用户关注的帖子,但我有一个问题。每次foreach循环都会返回一个用户及其帖子。 现在的情况:

关注的用户1

  • 帖子1
  • 帖子2
  • 帖子3等等

关注的用户2

  • 帖子1
  • 帖子2
  • 帖子3等等
我想要展示的内容:
  • 关注的用户1的帖子1
  • 关注的用户2的帖子1
  • 关注的用户2的帖子2
  • 关注的用户1的帖子2等等
有什么想法吗?

在你的模型中,你是如何设置关联的?看一下 hasManyThrough ,它可能正是你所需要的。 - Victor
2个回答

11
<?php
        /**
         * Get feed for the provided user
         * that means, only show the posts from the users that the current user follows.
         *
         * @param User $user                            The user that you're trying get the feed to
         * @return \Illuminate\Database\Query\Builder   The latest posts
         */
        public function getFeed(User $user) 
        {
            $userIds = $user->following()->lists('user_id');
            $userIds[] = $user->id;
            return \Post::whereIn('user_id', $userIds)->latest()->get();
        }

首先,您需要获取当前用户关注的用户及其ids,以便将其存储在$userIds中。

其次,您需要将您自己的帖子添加到数组中以使Feed中也包含您的帖子。

第三,您返回那些发布者或作者在第一步获取的数组中的帖子。

并且按照最新到最旧的顺序获取它们并存储它们。

欢迎提出任何问题!


谢谢回复!这似乎有效,但是我只是在视图中获取我的数据:[{"id":118696,"category_id":"win","user":56031,"username":等等。如何正确地将数据返回到我的视图中? - John
那个函数应该在你的模型或存储库中。然后你从控制器调用那个函数,将其存储在某个变量中,并通过View::make()函数传递它。 - Akar
谢谢你迄今为止的帮助 :) 我在从控制器调用函数方面遇到了困难,你能帮忙吗? - John
什么都没有,因为我遇到了这个错误:达到了“100”的最大函数嵌套级别,正在中止! - John
抱歉忘记接受您的答案了。最终成功解决了。感谢您的帮助!(我也想点赞,但我声望不够。) - John
显示剩余2条评论

3

针对Akar的回答做出一个更正:
对于那些在2020年来这里的人,你需要使用pluck而不是lists。在新版本的Laravel中发生了变化。

public function getFeed(User $user) 
        {
            $userIds = $user->following()->pluck('user_id');
            $userIds[] = $user->id;
            return \Post::whereIn('user_id', $userIds)->latest()->get();
        }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接