通过关注者laravel获取帖子

问题描述 投票:2回答:2

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

塔贝尔:

  • 帖子
  • 用户
  • 关注

用户模型:

 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

  • 帖子1
  • 帖子2
  • 发布3个等,等等

关注用户2

  • 帖子1
  • 帖子2
  • 发布3个等,等等

我想显示的是:

  • 关注的用户1发布1
  • 关注的用户2发布1
  • 关注的用户2发布2
  • 关注的用户1发布2等,等等

有什么想法吗?

php laravel laravel-4 model eloquent
2个回答
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中。

第二,您需要提要还包含您的帖子,因此您也将其添加到数组中。

第三,您返回帖子的posterauthor在第一步中获得的数组中的帖子。

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

欢迎任何问题!


0
投票

只是对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();
        }

© www.soinside.com 2019 - 2024. All rights reserved.