How do I get all children that fall under a parent in eloquent?

前端 未结 6 2096
日久生厌
日久生厌 2021-01-04 21:45

In my database, I have a Categories table. Categories can have parent categories, making it a recursive relationship

I also have a products table. Each product falls

6条回答
  •  走了就别回头了
    2021-01-04 22:28

    Say $category_id = Category->id and you want a collection of products as children of that category, I would try:

    $products = App\Product::with(['SubSubCategory.SubCategory.Category'=>function($query) use ($category_id) {$query->where('id', $category_id);}])->get();

    To be able to do so. You will need your 'one to many' inverse relationships to be as such:

    //App\SubCategory

    public function Category(){return $this->belongsTo('App\Category');}

    //App\SubSubCategory

    public function Sub_Category(){return $this->belongsTo('App\SubCategory');}

    //App\Product

    public function SubSubCategory(){return $this->belongsTo('App\SubSubCategory');}

    Good luck.

提交回复
热议问题