[英]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 我的laravel 5.3应用程序中有三个模型,其关系如下
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. 现在在我的控制器中我只有一个类别,我想要属于我所属类别的子类别中的所有帖子(按ID排序)。 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: 你需要的是使用hasManyThrough关系:
Category:
public function posts(){
return $this->hasManyThrough('App\Posts', 'App\Subcategory');
}
Then you can use it like this: 然后你可以像这样使用它:
$posts = $category->posts;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.