查询集合中的关系值

I have 3 tables, users > posts > comments. User has many posts and post has many comments. I am trying to get only comments from a user. Something like this:

$user->posts->comments->where(...)->get()
  • $user->posts returns a collection of collection of posts
  • Thus, if I try $user->posts->first()->comments, it returns collection of post's comments.

However, with the above scenario (posts->comments), it doesn't work because posts is a collection

I believe running a for loop is not the optimal way, even though I believe it can be achieved that way.

What is the Laravel way of achieving this?

You can use Has Many Through, see https://laravel.com/docs/5.5/eloquent-relationships#has-many-through.

In your User model:

public function comments()
{
    return $this->hasManyThrough('App\Comment', 'App\Post');
}