获取关注者laravel的帖子

时间:2015-02-22 00:45:03

标签: php laravel laravel-4 model eloquent

我想为经过身份验证的用户显示供稿页面,该页面显示他们关注的用户的最新帖子。我已经建立了一个跟踪系统,其中包含以下内容:

Tabels:

  • 帖子
  • 用户
  • 遵循

用户模型:

 public function follow() {  
    return $this->BelongsToMany( 'User', 'Follow' ,'follow_user', 'user_id');
}

饲料控制器:

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

  • Post 1
  • Post 2
  • Post 3 etc等

关注用户2

  • Post 1
  • Post 2
  • Post 3 etc等

我想要展示的内容:

  • 关注用户1发布1
  • 关注用户2发布1
  • 关注用户2帖子2
  • 关注用户1帖子2等

有什么想法吗?

2 个答案:

答案 0 :(得分:5)

<?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还包含您的帖子,因此您也将其添加到数组中。

第三,您返回的帖子中,该帖子的posterauthor位于我们从第一步获得的数组中。

抓住他们存储它们从最新到最旧。

欢迎任何问题!

答案 1 :(得分:1)

只是对 Akar 答案的更正:
对于2020年在这里的人,必须使用lists代替pluck。在新版本的laravel中发生了变化。

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

相关问题