繁体   English   中英

获取关注者的帖子 laravel

[英]Get posts by followers laravel

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

标签:

  • 帖子
  • 用户
  • 跟随

用户模型:

 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);

    }

进给刀片

  @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
        /**
         * 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该职位的是该数组中,我们从第一步了。

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

欢迎任何问题!

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM