Search code examples
phplaraveleloquentlaravel-5.3

How to handle multiple levels of one-to-many relationships in 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.


Solution

  • 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;