如何获取关注用户的帖子
How to get posts of followed users
我正在尝试制作新闻提要页面,但在此页面中我需要输出 articles
按日期排序并且它们必须属于用户,授权用户遵循。我尝试了几件事,然后意识到我的逻辑错误。所以在 user model
我有:
function followers()
{
return $this->belongsToMany('App\User', 'followers', 'user_id', 'follower_id');
}
function follows()
{
return $this->belongsToMany('App\User', 'followers', 'follower_id', 'user_id');
}
function articles(){
return $this->hasMany('App\Article');
}
比 article
我有以下关系:
public function user()
{
return $this->belongsTo('App\User');
}
我不知道我是否可以简单地获取所有文章而不是输出用户关注的文章。我有点困惑。
这是我在控制器中使用的代码:
$followinguserarticle = Article::whereHas('user.follows', function($q) {
$q->where('id', auth()->id());
})
->latest()
->get();
然后我尝试通过它们循环:
@foreach($followinguserarticle as $followinguserarticles)
<a>followinguserarticles->title</a>
@endforeach
使用 whereHas()
:
Article::whereHas('user.followers', function($q) {
$q->where('id', auth()->id());
})
->latest()
->get();
您可以在 authed 用户实例
上 eager load 关系
$authed = Auth::user();
$authed ->load('follows.articles');
现在您有用户关注的用户的文章
foreach($authed->follows as $follow){
foreach($follow->articles as $article){
//Now you have access to each article
}
}
所以我找到的解决方案是这样的:
//get list of follower ids
$follows = Auth::user()->follows->pluck('id');
//get articles of those that user follows
$articles = Article::whereIn('user_id',$follows)
->with('user')
->latest()
->limit(10)
->get();
我正在尝试制作新闻提要页面,但在此页面中我需要输出 articles
按日期排序并且它们必须属于用户,授权用户遵循。我尝试了几件事,然后意识到我的逻辑错误。所以在 user model
我有:
function followers()
{
return $this->belongsToMany('App\User', 'followers', 'user_id', 'follower_id');
}
function follows()
{
return $this->belongsToMany('App\User', 'followers', 'follower_id', 'user_id');
}
function articles(){
return $this->hasMany('App\Article');
}
比 article
我有以下关系:
public function user()
{
return $this->belongsTo('App\User');
}
我不知道我是否可以简单地获取所有文章而不是输出用户关注的文章。我有点困惑。
这是我在控制器中使用的代码:
$followinguserarticle = Article::whereHas('user.follows', function($q) {
$q->where('id', auth()->id());
})
->latest()
->get();
然后我尝试通过它们循环:
@foreach($followinguserarticle as $followinguserarticles)
<a>followinguserarticles->title</a>
@endforeach
使用 whereHas()
:
Article::whereHas('user.followers', function($q) {
$q->where('id', auth()->id());
})
->latest()
->get();
您可以在 authed 用户实例
上 eager load 关系$authed = Auth::user();
$authed ->load('follows.articles');
现在您有用户关注的用户的文章
foreach($authed->follows as $follow){
foreach($follow->articles as $article){
//Now you have access to each article
}
}
所以我找到的解决方案是这样的:
//get list of follower ids
$follows = Auth::user()->follows->pluck('id');
//get articles of those that user follows
$articles = Article::whereIn('user_id',$follows)
->with('user')
->latest()
->limit(10)
->get();