簡體   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