我想为经过身份验证的用户显示一个供稿页面,其中显示了他们关注的用户的最新帖子。我已经建立了一个追踪系统,该系统具有以下内容:
塔贝尔:
用户模型:
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
我想显示的是:
有什么想法吗?
<?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年在这里的人,必须使用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();
}