我有多级别类别,其结构如下:
Parent - first child -- second child - another 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',$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')); }
楷模
产品型号
public function category(){ return $this->belongsTo(Category::class); }
分类模型
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); }
任何想法?
你可以通过简单的技巧获得嵌套的孩子.
原文链接:https://www.f2er.com/laravel/138823.html只使用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'); } 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); }
现在你可以使用Childs了
Category::with('childs')->get();
希望这可以帮助.