Eloquent Parent-Child relationship on same model

前端 未结 6 1492
醉酒成梦
醉酒成梦 2020-12-03 07:42

I have a model CourseModule, and each of the items are related to the same model.

Database Structure:

Relation in Model:



        
6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-03 08:08

    You should use with('children') in the children relation and with('parent') in the parent relations.

    For your code to be recursive:

    public function parent()
    {
        return $this->belongsTo('App\CourseModule','parent_id')->where('parent_id',0)->with('parent');
    }
    
    public function children()
    {
        return $this->hasMany('App\CourseModule','parent_id')->with('children');
    }
    

    Note: Make sure your code has some or the other exit conditions otherwise it will end up in a never ending loop.

提交回复
热议问题