Laravel 如何得到的人,我下面的雄辩的职位
我有一个Laravel 如何得到的人,我下面的雄辩的职位,laravel,eloquent,Laravel,Eloquent,我有一个User模型,一个Post模型 在我的用户模型中,我有以下内容: public function followers() { return $this->belongsToMany(User::class, 'followers', 'follower_id', 'user_id')->withTimestamps(); } public function following() { return $this->belongsToMany(User:
User
模型,一个Post
模型
在我的用户
模型中,我有以下内容:
public function followers()
{
return $this->belongsToMany(User::class, 'followers', 'follower_id', 'user_id')->withTimestamps();
}
public function following()
{
return $this->belongsToMany(User::class, 'followers', 'user_id', 'follower_id')->withTimestamps();
}
public function posts()
{
return $this->hasMany(Post::class);
}
所以基本上,$user->following
给我一个我正在跟踪的用户集合,$user->posts
给我一个posts集合。我想这样做:
$posts = [];
$user->following->each(function($f) use($posts) {
$posts[] = $f->posts;
});
但更雄辩的方式,如果这有意义的话。因为我想在这之后对结果进行分页。我想做hasManyThrough
,但不知道怎么做?是链接到类似问题的答案
我想你应该这样做:
User::where('id', $id)->with(['following.posts' => function ($q) use (&$posts) {
$posts= $q->get()->unique();
}])->first();
一个用户将有许多帖子,一个用户将有许多追随者。但我无法通过“通过”关注者看到用户和帖子之间的关系。