获取关注者laravel的帖子

Joh*_*ohn 2 php model laravel eloquent laravel-4

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

Tabels:

  • 帖子
  • 用户
  • 跟随

用户模型:

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

进料控制器:

public function feed () {

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

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

    }
Run Code Online (Sandbox Code Playgroud)

Feed.blade

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

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

     //* post data here.

  @endforeach

 @endforeach
Run Code Online (Sandbox Code Playgroud)

这是从用户跟随的用户拉出的帖子,但是,我有一个问题.foreach每次返回一个用户,然后返回他们的帖子.

它现在在做什么:

跟随用户1

  • 发布1
  • 发布2
  • 邮政3等等

跟随用户2

  • 发布1
  • 发布2
  • 邮政3等等

我要展示的内容:

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

有任何想法吗?

Aka*_*kar 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();
        }
Run Code Online (Sandbox Code Playgroud)

首先,您需要获取当前用户所关注的用户以及他们ids可以存储的用户$userIds.

其次,您需要Feed还包含您的帖子,因此您也将其添加到数组中.

第三,你返回岗位,其中posterauthor该职位的是数组,我们从第一步得到英寸

并抓住他们存储从最新到最旧.

欢迎任何问题!