Search code examples
phplaravelalgorithmrecursive-datastructures

laravel recursive relationship with directed acyclic graph


i have table "task" and relationship many to many with itself

    public function depends_on() //parents
    {
        return $this->hasMany(DependentTask::class, 'task_id');
    }

    public function dependents() //kids
    {
        return $this->hasMany(DependentTask::class, 'dependent_id');
    }

the relationship may be like this

the relationship may be like this

i want to select the tasks like this

first print 5 or 2

then 3 and 6

then 4 and 1

how can i do it by laravel?


Solution

  • This is how you can use recursive relations:

    public function dependsOn()
    {
        return $this->hasMany('Account', 'task_id','dependent_id');
    }
    
    public function dependents()
    {
       return  $this->dependsOn()->with('dependents');
    
    }
    

    Then:

    $dependents = Dependents::with('dependents')->first();
    
    $dependents->dependents; 
    
    $dependents->dependents->first()->dependents; // .. and so on