[英]Get full path of nested parents
我有一个名为Source
的模型,其中包含一个parent_id
列。 每个源都可以具有parent_id
,并且层次结构是无限的。 如果Source
没有parent_id
,则它是根。
现在,我的模型中目前有以下方法:
public function parent()
{
return $this->hasOne('App\Source', 'id', 'parent_id');
}
public function children()
{
return $this->hasMany('App\Source', 'parent_id')->orderBy('name');
}
我毫不费力地获得了一个很好的孩子名单,例如:
$parents = Source::with('children')->whereNull('parent_id')->orderBy('name')->get();
$traverse = function ($parents, $prefix = '') use (&$traverse) {
foreach ($parents as $parent) {
echo '<option value="'.$parent->id.'">'.$prefix.$parent->name.'</option>';
$traverse($parent->children, $prefix.'- ');
}
};
$traverse($parents);
我的问题是我想获得模型名称的完整字符串及其父名称。
所以说我有以下来源:
Parent 1
- Child 1
- - Subchild 1
- - Subchild 2
- Child 2
我正在尝试创建一个函数,该函数在调用Parent 1 - Child 1 - Subchild 1
时将给我Parent 1 - Child 1 - Subchild 1
Subchild 1
这是我尝试过的方法,似乎只为我提供了顶级父名称:
public static function treeName(Source $source, &$tree)
{
if ($source->parent) {
$tree[] = self::treeName($source->parent, $tree);
}
else {
$tree[] = $source->name;
}
}
$source = Source::where('name', 'Subchild 1')->first();
$tree = [];
Source::treeName($source, $tree);
Log::info($tree);
这给了我:
[2018-04-25 23:02:25] laravel.INFO: array (
0 => 'Parent 1',
1 => NULL,
2 => NULL,
)
我可以通过以下方式简单地使数组内爆-
但数组无法满足我的需求。 我该如何工作?
这是我想要的:
array (
0 => 'Parent 1',
1 => 'Child 1',
2 => 'Subchild 1',
)
这应该在数组中为您提供所需的结果:
function toArray($child) {
$tree = [];
while($child) {
// Prepand the name to the front of the array
array_unshift($tree, $child->name);
// Overwrites `$child` with it's parent, for next iteration
// If the parent doesn't exist, $child will be null
// which will also end the `while` loop
$child = $child->parent;
}
return $tree;
}
将其传递给孩子的对象,它将返回数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.