且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Laravel 获取祖先(URL)

更新时间:2023-11-26 10:15:10

在评论中进行了一些交谈后,我认为这是一个很好的解决方案:

After a little conversation in the comments I think this is a good solution:

// 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;
}

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

Then you can retrieve your parents using:

  • YourModel::find(123)->parents (collection instance)
  • YourModel::find(123)->parents->implode('yourprop', '/') (imploded to string, see https://laravel.com/docs/5.4/collections#method-implode)
  • YourModel::find(123)->parents->reverse()->implode('yourprop', '/') (reversed order https://laravel.com/docs/5.4/collections#method-reverse)

正如 Nikolai Kiselev https://***.com/a/55103589/1346367 所指出的,您也可以将它组合起来这样可以节省一些查询:

As noted by Nikolai Kiselev https://***.com/a/55103589/1346367 you may also combine it with this to save a few queries:

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

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

This preloads the parent on object load. If you decide not to use this, the parent is (lazy) loaded as soon as you call $yourModel->parent.