简体   繁体   中英

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM