laravel 与有向无环图的递归关系

laravel recursive relationship with directed acyclic graph

我有table“任务”和多对多关系

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

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

关系可能是这样

我想select这样的任务

首先打印 5 或 2

然后是 3 和 6

然后是 4 和 1

我怎样才能做到 laravel?

这是使用递归关系的方式:

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

public function dependents()
{
   return  $this->dependsOn()->with('dependents');

}

然后:

$dependents = Dependents::with('dependents')->first();

$dependents->dependents; 

$dependents->dependents->first()->dependents; // .. and so on