Laravel Get ancestors (URL)

后端 未结 2 1790
一生所求
一生所求 2021-01-19 18:08

In Laravel, I have a table which contains id, parent_id, slug (Self-referring),

When I have an ID, I need to get all its ancestors in a format like this (Separated b

2条回答
  •  没有蜡笔的小新
    2021-01-19 18:20

    If you know how many levels maximum could be nested you can use Eager Loading. Let's say if maximum depth is 3 levels you can do:

    $model->with('parent.parent.parent');
    

    You can also use recursion instead of loop.

    public function getParentsAttribute()
    {
        if (!$this->parent) {
            return collect([]);
        }
    
        return collect($this->parent->parents)->push($this->parent);
    }
    

    In case you want to add the first one object too (self) the full call will be:

    $model->parents->push($model)->reverse->implode('attr_name', '/');
    

    Which you can also wrap into attribute

    public function getPathAttribute() {
        return $model->parents->push($model)->reverse->implode('attr_name', '/');
    }
    

    And call like $model->path;

提交回复
热议问题