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

前端 未结 6 2097
日久生厌
日久生厌 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:26

    Suppose your Model name is Category

    Create a function on Category model

    public function children() { return $this->hasMany('App\Category', 'parent_id', 'id'); }
    

    Using above method on your controller

    $categories = Category::with('children')->where('parent_id',0)->get();
    

提交回复
热议问题