我有一个网站建立在laravel。网站由用户组成,用户可以互相关注。Users
可以制作Shoutouts
(类似于tweet),并且相互关注的用户应该能够看到这些。我在我的数据库中有一个User
表,一个Shoutout
表和一个Follow
表。
在Laravel中,用户与大喊和跟随表都有hasMany
关系。
当用户登录时,我想要获取该用户关注的所有人。我可以这样做:
$following = Follow::whereUser_id($user->id)->get();
然而,我现在如何从$following
中的用户获得Shoutouts
,从创建呼喊的时间降序,所以我可以在我的视图中执行foreach($呼喊作为$呼喊)?这个想法是,用户可以看到用户关注的人的最新大喊大叫。
如果我这样做:
$following = Follow::whereUser_id($user->id)->get();
foreach($following as $follow) {
$shoutouts = $shoutouts . Shoutout::whereUser_id($follow->user_id)->get();
}
我将以不正确的顺序获得它们,因为这会让我将特定用户的所有大喊大叫放在一起,但我希望将它们按降序排列,以便用户首先看到最新的大喊大叫。
感谢所有的帮助。
您可以尝试使用join
作为:
假设您的Follow
表中有一个followed_user_id
。
$shoutouts = Shoutout::join('follow', 'shoutout.user_id', '=', 'follow.followed_user_id')
->where('follow.user_id', $user->id)
->select(''shoutout.*'')
->orderBy('shoutout.created_at', 'desc')
->get()
您要在您关注的用户的大喊中寻找https://laravel.com/docs/5.3/eloquent-relationships#eager-loading。如果您正确定义了关系,您应该能够:
$following = Follow::whereUser_id($user->id)->with('shoutouts')->get();
然后按用户输入:
foreach($following as $follow) {
$shoutouts = $follow->shoutouts;
//Do Something With The Collection Of Shoutouts
}
为了得到用户的呼喊,你可以在用户表上定义一个hasManyThrough
:
public function followerShoutouts()
{
return $this->hasManyThrough(Shoutout::class, Follow::class, 'user_id', 'user_id_being_followed');
}
那么你可以这样做:
$shoutouts = User::with(['followerShoutouts' => function($query) {
return $query->orderBy('created_at', 'desc');
}])->find($userId);