我想为经过身份验证的用户显示供稿页面,该页面显示他们关注的用户的最新帖子。我已经建立了一个跟踪系统,其中包含以下内容:
Tabels:
用户模型:
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
关注用户2
我想要展示的内容:
有什么想法吗?
答案 0 :(得分: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
中。
其次,您需要Feed还包含您的帖子,因此您也将其添加到数组中。
第三,您返回的帖子中,该帖子的poster
或author
位于我们从第一步获得的数组中。
抓住他们存储它们从最新到最旧。
欢迎任何问题!
答案 1 :(得分:1)
只是对 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();
}