php – 在laravel中获取父类别中的子类别信息
发布时间:2020-12-14 19:49:55 所属栏目:大数据 来源:网络整理
导读:我有多级别类别,其结构如下: Parent - first child -- second child - another child 我想要做的是,在父页面的所有子级别中获取产品,以便我可以拥有父级,第一个孩子,第二个孩子,父母中的另一个孩子的所有产品. 我到目前为止,目前我可以得到父母,第一个孩子
我有多级别类别,其结构如下:
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); } 任何想法?
你可以通过简单的技巧获得嵌套的孩子.
只使用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(); 希望这可以帮助. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |