Eloquent Parent-Child relationship on same model

前端 未结 6 1486
醉酒成梦
醉酒成梦 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:16

    your model relationship should like this

         // parent relation
         public function parent(){
    
            return $this->belongsTo(self::class , 'parent_id');
        }
        //child relation
         public function children()
        {
            return $this->hasMany(self::class ,'parent_id');
        }
        public function ascendings()
        {
            $ascendings = collect();
    
            $user = $this;
    
            while($user->parent) {
                $ascendings->push($user->parent);
    
                if ($user->parent) {
                    $user = $user->parent;
                }
            }
    
            return $ascendings;
        }
    
    
    
        public function descendings()
        {
            $descendings = collect();
            $children = $this->children;
    
            while ($children->count()) {
    
                $child = $children->shift();
    
                $descendings->push($child);
    
                $children = $children->merge($child->children);
    
            }
            return $descendings;
        }
    

提交回复
热议问题