[英]Laravel 5: How to get all adverts from a category including all subcategories
I have the following models and relations 我有以下模型和关系
class Advert extends Model
{
public function category() {
return $this->belongsTo('App\Category');
}
}
class Category extends Model
{
public function parent() {
return $this->belongsTo('App\Category', 'category_id','id');
}
public function children() {
return $this->hasMany('App\Category', 'category_id');
}
public function adverts() {
return $this->hasMany('App\Advert');
}
}
I have table with adverts who belong to a category ... The advert's category can be a subcategory of another category ... Subcategory level is max 4. How can i retrieve all the adverts from all subcategories through the main root category it belongs. 我的桌子上有属于某个类别的广告...该广告的类别可以是另一个类别的子类别...子类别级别最高为4。如何通过其所属的主根类别从所有子类别中检索所有广告。
For example 例如
<ul> <li>Smartphones <ul> <li>Android <ul> <li>Samsung</li> <li>Huawei</li> <li>LG</li> <li>Meizu</li> <li>Acer</li> </ul> </li> <li>Apple <ul> <li>iPhone 5</li> <li>iPhone 6</li> <li>iPhone X</li> </ul> </li> </ul> </li> </ul>
How can i get all adverts from all subcategories for example if i click on Smartphones ... Do i have to iterate through each level or there is an easier solution with relations... 我如何从所有子类别中获取所有广告,例如,如果我单击“智能手机” ...我是否必须遍历每个级别,或者有一种更简单的关系解决方案...
Thanks 谢谢
you can make relations recursive 你可以使关系递归
class Advert extends Model
{
public function category() {
return $this->belongsTo('App\Category');
}
}
class Category extends Model
{
public function parent() {
return $this->belongsTo('App\Category', 'category_id','id');
}
public function parentRecursive()
{
return $this->parent()->with('parentRecursive');
}
public function children() {
return $this->hasMany('App\Category', 'category_id');
}
public function childrenRecursive()
{
return $this->children()->with('childrenRecursive');
}
public function adverts() {
return $this->hasMany('App\Advert');
}
}
for getting adverts with recursive results 用于获得具有递归结果的广告
$adverts = Advert::with('Category')
->with('Category.childrenRecursive')->whereNull('Category.parent')->get();
Try to use nested sets package. 尝试使用嵌套集程序包。 It is awesome and easily do this work.
很棒而且很容易完成这项工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.