[英]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
關注用戶 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
。
其次,您需要提要也包含您的帖子,因此您也將其添加到數組中。
第三,你返回崗位,其中poster
或author
該職位的是該數組中,我們從第一步了。
並抓住它們從最新到最舊存儲它們。
歡迎任何問題!
只是對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.