【问题标题】:laravel recursive relationship with directed acyclic graphlaravel与有向无环图的递归关系
【发布时间】:2021-10-28 08:53:45
【问题描述】:

我有表“任务”和自己的多对多关系

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

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

关系可能是这样的

我想选择这样的任务

先打印 5 或 2

然后是 3 和 6

然后是 4 和 1

我如何通过 laravel 做到这一点?

【问题讨论】:

    标签: php laravel algorithm recursive-datastructures


    【解决方案1】:

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

    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
    

    【讨论】:

    猜你喜欢
    • 2017-05-31
    • 2014-12-26
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2011-01-23
    • 2021-09-05
    • 2020-06-12
    相关资源
    最近更新 更多