[英]Get all parents of child category
I would like to get all of its main categories if the product category is a subcategory.如果产品类别是子类别,我想获取其所有主要类别。
I read this article: Laravel get all parents of category .but I could not adapt my own project我读了这篇文章: Laravel 获得了所有类别的父母。但我无法适应我自己的项目
I have one category table in DB.我在数据库中有一个类别表。 - category And if category is the main category his main_id = 0 but if it subcategory main_id is parent id.
- 类别 如果类别是主类别,则他的 main_id = 0 但如果它是子类别 main_id 是父 id。 İ need to get categories like that sub->parent->parent....Parent How can i do this?
我需要获得这样的类别 sub->parent->parent....Parent 我该怎么做? Thanks
谢谢
My Category model我的类别模型
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');
}
}
You would get the parents like this:你会得到这样的父母:
$category = Category::find(1);
$collection = collect();
do {
$collection->push($category->parent);
$category = $category->parent;
} while($category->parent()->exists())
Keep in mind that this method ends up with the $category
variable as the highest parent in the chain.请记住,此方法最终将
$category
变量作为链中的最高父级。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.