I have multi level category where structure is like:
Parent
- first child
-- second child
- another child
What I want to do is, getting products in all child levels in Parent Page
so that I can have all products of parent, first child, second child, another child
inside Parent
.
What I have so far, currently I can get products of Parent, first child & another child
but I'm not able to get products of my second child
.
Codes
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'));
}
models
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);
}
any idea?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…