首页 > 解决方案 > 在laravel的父类别中获取子类别信息

问题描述

我有多层类别,其中结构如下:

Parent
 - first child
  -- second child
 - another child

我想要做的是,获取所有子级别的产品,Parent Page以便我可以拥有parent, first child, second child, another childinside的所有产品Parent

到目前为止我所拥有的,目前我可以获得产品,Parent, first child & another child但我无法获得我的产品second child

代码

public function totalcategoriessubs($catslug) {
    $category = Category::where('slug','=',$catslug)->with('childs')->first();
    //testing this
    // $products = Product::whereHas('category', function($q) use ($catslug,$category)
    // {
    //   $q->where(function($q) use ($catslug,$category) {
    //     $q->where('slug',$catslug)->orWhere('category_id',$category->id);
    //   });
    // })->orderBy('created_at', 'DESC')->paginate(10);

    $products = Product::whereHas('category', function($q) use ($catslug, $category) {
      $q->where(function($q) use ($catslug,$category) {
        $q->where('slug',$catslug) //works
          ->WhereHas('childs') //works
          ->WhereHas('childs.childs') //not working
          ->orWhere('category_id',$category->id); //works
        });
      })->orderBy('created_at', 'DESC')->paginate(10);
    //end testing
    return view('front.categoriessubs', compact('products', 'category'));
  }

楷模

Product model

public function category(){
     return $this->belongsTo(Category::class);
}

Category model

public function categories()
  {
    return $this->hasMany(Category::class);
  }

  public function childs() {
    return $this->hasMany(Category::class,'category_id','id') ;
  }

  public function parent()
  {
      return $this->belongsTo(Category::class,'category_id');
  }

  public function isParent()
  {
      return !$this->category_id ? true : false; // if category_id is null => is a Parent Category
  }

  public function products(){
     return $this->hasMany(Product::class);
  }

任何想法?

标签: phplaravel

解决方案


您可以通过简单的技巧获得嵌套的孩子。

protected $appends = ['childs', 'products'];在模型中使用。

在 Category.php 模型中

protected appends = ['childs'];


public function categories()
  {
    return $this->hasMany(Category::class);
  }

  public function childs() {
    return $this->hasMany(Category::class,'category_id','id') ;
  }

  public function parent()
  {
      return $this->belongsTo(Category::class,'category_id');
  }

  public function isParent()
  {
      return !$this->category_id ? true : false; // if category_id is null => is a Parent Category
  }

  public function products(){
     return $this->hasMany(Product::class);
  }

现在你可以让孩子们使用

Category::with('childs')->get();

希望这可以帮助。


推荐阅读