从儿童集合中获取所有父母记录

时间:2019-02-07 19:24:15

标签: laravel

我已经遇到过几次,但从来不知道获取正确集合的正确方法。假设用户拥有

  1. 回复
  2. 线程

我想让用户使用Threads的所有reply。数据库看起来像

回复

ID  |  thread_id  |  user_id  |  body

线程

ID  |  user_id  |  channel_id  |  title  |  body

我知道我可以做$user->replies,然后遍历它们并检索$reply->thread,但这感觉不正确。我看过hasManyTrough,但这似乎也不对,或者我只是听不懂。似乎这种情况很常见。

1 个答案:

答案 0 :(得分:0)

假设您的关系如下:

class User extends Model 
{
    public function threads()
    {
        return $this->hasMany(Thread::class); 
    }
}

class Thread extends Model 
{
    public function user()
    {
        return $this->belongsTo(User::class); 
    }

    public function replies()
    {
        return $this->hasMany(Reply::class); 
    }
}

class Reply extends Model 
{
    public function user()
    {
        return $this->belongsTo(User::class); 
    }

    public function thread()
    {
        return $this->belongsTo(Thread::class); 
    }
}

您可以添加一个whereHas()子句,如下所示:

$user = auth()->user();

Thread::with('user')
    ->whereHas('replies', function($query) use($user) {
        $query->where('user_id', $user->id); 
    })
    ->get(); 

以上内容将获取所有具有至少一个属于指定用户的答复的线程。