Eloquent Parent-Child relationship on same model

前端 未结 6 1479
醉酒成梦
醉酒成梦 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 07:55

    here is the answer that can help you

    I think you you have to do it recursively to retrieve whole tree:

    $data = CourseModule::with('child_rec');
    

    Recursive function

    This may help you according to your requirement,

    public function child()
    {
       return $this->hasMany('App\CourseModule', 'parent');
    }
    public function children_rec()
    {
       return $this->child()->with('children_rec');
       // which is equivalent to:
       // return $this->hasMany('App\CourseModule', 'parent')->with('children_rec);
    }
    // parent
    public function parent()
    {
       return $this->belongsTo('App\CourseModule','parent');
    }
    
    // all ascendants
    public function parent_rec()
    {
       return $this->parent()->with('parent_rec');
    }
    

提交回复
热议问题