Laravel - Sub-categories display under Main categories

前端 未结 2 1317
我寻月下人不归
我寻月下人不归 2021-01-15 04:52

Hi there
I have one problem with categories and sub-categories
I have table like:

ID----- Name---- ParentID
1 ------- A ---------

2条回答
  •  伪装坚强ぢ
    2021-01-15 05:42

    Using Eloquent you can use a hasMany() relationship to relate the table to itself.

    Try creating a new method on your model, like so:

    class Category extends Eloquent 
    {
    
        ...
    
        public function children()
        {
            return $this->hasMany('Category','ParentId');   
        }
    }
    

    Then you should be able to get a list of sub categories for any given ID.

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

    Alternatively, the query suggested by deczo in the comments is a lot simpler, I would recommend using this instead.

    Category::with('children')->find(1);
    

提交回复
热议问题