Сгладить вложенные отношения laravel (от родителя к потомкам)Php

Кемеровские программисты php общаются здесь
Ответить
Anonymous
 Сгладить вложенные отношения laravel (от родителя к потомкам)

Сообщение Anonymous »

В моей модели есть отношения родитель-потомок. Я хочу сгладить всю эту коллекцию, включая всех потомков родителя.

Код: Выделить всё

[
{
'name': 'Parent',
'another_array' => [

{
'name': 'Another Array Name'
}
],
'children': [
{
'name': 'First Child',
'address': 'lorem ipsum',
'contact_no': '92390',

'another_array' => [

{
'name': 'Another Array Name'
}
],
'children': [
{
'name': 'First Descendant',
'address': 'lorem ipsum',
'contact_no': '92390',
'children': [
{
'name': 'Descendant Child',
'address': 'lorem ipsum',
'contact_no': '92390',
'children': [
{
'name': 'Last Descendant',
'address': '',
'contact_no': '',
'children': []
}
]

}
]
}
]
}
]
}
]

Я попробовал код ниже. Однако он отображает только вторую глубину детей. Следующие дочерние элементы коллекции не отображаются.

Код: Выделить всё

User.php
public function parent()
{
return $this->belongsTo(User::class, 'id', 'parent_id');
}

public function children()
{

return $this->hasMany(User::class,'parent_id', 'id');
}

public function descendants()
{
return $this->children()->with('descendants');
}

UsersController.php

public function index()
{
$parent = User::find(1);

$parent->with('descendants')->find($parent->id);

$descendants = $this->traverseTree($parent->descendants);

return response($descendants);
}

protected function traverseTree($subtree)
{
$descendants = collect([]);

foreach ($subtree->descendants as $descendant) {

$descendants->push($descendant);

if($descendant->descendants instanceof Collection) {

foreach ($descendant->descendants as $node) {

$this->traverseTree($node);

$descendants->push($node);
}
}
}

return $descendants;
}
Желаемый результат

Код: Выделить всё

[
{
'name': 'Parent',
'address': 'lorem ipsum',
'contact_no': '92390'
},
{
'name': 'First Child',
'address': 'lorem ipsum',
'contact_no': '92390'
},
{
'name': 'First Descendant',
'address': 'lorem ipsum',
'contact_no': '92390',
},
{
'name': 'Descendant Child',
'address': 'lorem ipsum',
'contact_no': '92390',
},
{
'name': 'Last Descendant' ,
'address': '',
'contact_no': '',
}

]

Жду вашей помощи.

Подробнее здесь: https://stackoverflow.com/questions/570 ... escendants
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Php»