【发布时间】:2019-07-08 16:00:31
【问题描述】:
如果产品类别是子类别,我想获取其所有主要类别。
我读了这篇文章:Laravel get all parents of category。但是我无法适应我自己的项目
我在数据库中有一个类别表。 - 类别 如果类别是主类别,他的 main_id = 0 但如果它的子类别 main_id 是父 id。 我需要获得像 sub->parent->parent....Parent 这样的类别 我怎样才能做到这一点?谢谢
我的类别模型
class Category extends Model
{
protected $table = 'category';
protected $fillable = ['category_name', 'slug', 'main_id'];
public function index() {
return $this->belongsTo('App\SubCategory');
}
public function productt(){
return $this->belongsToMany('App\SubCategory','category_sub');
}
public static function getCategory($parent = 0, $string = '-1'){
$categories = Category::where('main_id', '=', $parent)->get();
$string = $string+1;
foreach($categories as $category){
echo "<option value='$category->id'>".str_repeat('-',
$string).$category->category_name."</option>";
Category::getCategory($category->id, $string);
}
}
public function parent()
{
return $this->belongsTo('App\Models\Category', 'main_id');
}
public function children()
{
return $this->hasMany('App\Models\Category', 'main_id');
}
}
【问题讨论】: