【问题标题】:Get all parents of child category获取子类别的所有父母
【发布时间】: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');
}

}

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    你会得到这样的父母:

    $category = Category::find(1);
    $collection = collect();
    do {
        $collection->push($category->parent);
        $category = $category->parent;
    } while($category->parent()->exists())
    

    请记住,此方法最终以 $category 变量为最高 链中的父级。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      • 2021-12-02
      • 2019-05-02
      • 2013-11-23
      相关资源
      最近更新 更多