我有以下模特和关系
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');
}
}
我有一个广告属于一个类别的表...广告的类别可以是另一个类别的子类别...子类别级别是最大值4.我如何通过所有子类别检索所有广告它所属的主要根类别。
例如
<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>
&#13;
如果我点击智能手机,我如何获得所有子类别的所有广告...我是否必须遍历每个级别,或者有一个更简单的关系解决方案......
谢谢
答案 0 :(得分:0)
你可以使关系递归
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');
}
}
获取递归结果的广告
$adverts = Advert::with('Category')
->with('Category.childrenRecursive')->whereNull('Category.parent')->get();
答案 1 :(得分:0)
尝试使用nested sets包。它很棒,很容易做这项工作。