微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php-Laravel获取祖先(URL)

在Laravel中,我有一个表,其中包含id,parent_id,slug(自引用),

我有一个ID时,我需要以这种格式(由“ /”分隔)获取其所有祖先.

level1/level2/level3

但是以一种高效的方式,没有像“ laravel-nestedset”这样的软件包
”.

我已经这样实现了.

public function parent()
{
    return $this->belongsTo('Collection', 'parent_id');
}

public function getParentsAttribute()
{
    $parents = collect([]);

    $parent = $this->parent;

    while(!is_null($parent)) {
        $parents->push($parent);
        $parent = $parent->parent;
    }

    return $parents;
}

还有其他有效的方式并用“ /”分隔吗?

解决方法:

经过一段简短的评论后,我认为这是一个不错的解决方案:

// YourModel.PHP

// Add this line of you want the "parents" property to be populated all the time.
protected $appends = ['parents'];

public function getParentsAttribute()
{
    $collection = collect([]);
    $parent = $this->parent;
    while($parent) {
        $collection->push($parent);
        $parent = $parent->parent;
    }

    return $collection;
}

然后,您可以使用以下方法检索父母:

> YourModel :: find(123)-> parents(集合实例)
> YourModel :: find(123)-> parents-> implode(‘yourprop’,’/’)(内爆到字符串,请参见https://laravel.com/docs/5.4/collections#method-implode)
> YourModel :: find(123)-> parents-> reverse()-> implode(‘yourprop’,’/’)(颠倒顺序https://laravel.com/docs/5.4/collections#method-reverse)

正如nikolai Kiselev https://stackoverflow.com/a/55103589/1346367所指出的那样,您也可以将其与此结合以保存一些查询

protected $with = ['parent.parent.parent'];
// or inline:
YourModel::find(123)->with(['parent.parent.parent']);

这会在对象加载时预加载父对象.如果您决定不使用它,则在您调用$yourModel-> parent时就会(延迟)加载父对象.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐