如何在laravel中处理多级别的一对多关系

I have three models in my laravel 5.3 application with relationships as follow

Category:

public function subcategories(){
    return $this->hasMany('App\Subcategory');
}


Subcategory:

public function category(){
    return $this->belongsTo('App\Category');
}

public function posts(){
    return $this->hasMany('App\Posts');
}


Post:

public function subcategory(){
    return $this->belongsTo('App\Subcategory');
}

Now in my controller I only have a category and I want all the posts (ordered by id) that are in the subcategories which belong to the category I have. Something like:

$posts = $category->subcategories->posts;

But I don't know how to do that. Help will be appreciated.

Hey Ahmed

What you need is the use of the hasManyThrough relation:

Category:

public function posts(){
    return $this->hasManyThrough('App\Posts', 'App\Subcategory');
}

Then you can use it like this:

$posts = $category->posts;