Return 条记录,其中 children 在 parents 下
Return records where children are under parents
我正在检索这样的模型 $people = Person::with('children')->get();
和这个 returns 我 dd($people);
Collection {#322 ▼
#items: array:4 [▼
0 => Person {#311 ▶}
#relations: array:1 [▼
"children" => Collection {#320 ▼
#items: array:2 [▼
0 => Child {#323 ▶}
1 => Child {#324 ▶}
1 => Person {#312 ▶}
2 => Person {#313 ▶}
#relations: array:1 [▼
"children" => Collection {#320 ▼
#items: array:2 [▼
0 => Child {#323 ▶}
3 => Person {#314 ▶}
但现在我正在尝试将其导出到 excel(Maatwebsite/Laravel-Excel 以查看)但我需要像这样(children 在他们的 parent 下),例如:
Collection {#322 ▼
#items: array:6 [▼
0 => Person {#311 ▶} // Parent 1
1 => Child {#312 ▶} // Child of parent 1
2 => Child {#313 ▶} // Child of parent 1
3 => Person {#314 ▶} // Parent 2 - Single (no relation)
4 => Person {#315 ▶} // Parent 3
5 => Child {#316 ▶} // Child of parent 3
6 => Person {#314 ▶} // Parent 4 - Single (no relation)
我不确定如何执行此操作(Eloquent 或查询生成器)?
我没试过,但我猜这样的东西会起作用:
$c = collect([]);
foreach($people as $person)
{
$children = $person->children;
$c->add($person);
if(count($children) > 0)
{
foreach($children as $child)
{
$c->add($child);
}
}
}
dd($c);
我正在检索这样的模型 $people = Person::with('children')->get();
和这个 returns 我 dd($people);
Collection {#322 ▼
#items: array:4 [▼
0 => Person {#311 ▶}
#relations: array:1 [▼
"children" => Collection {#320 ▼
#items: array:2 [▼
0 => Child {#323 ▶}
1 => Child {#324 ▶}
1 => Person {#312 ▶}
2 => Person {#313 ▶}
#relations: array:1 [▼
"children" => Collection {#320 ▼
#items: array:2 [▼
0 => Child {#323 ▶}
3 => Person {#314 ▶}
但现在我正在尝试将其导出到 excel(Maatwebsite/Laravel-Excel 以查看)但我需要像这样(children 在他们的 parent 下),例如:
Collection {#322 ▼
#items: array:6 [▼
0 => Person {#311 ▶} // Parent 1
1 => Child {#312 ▶} // Child of parent 1
2 => Child {#313 ▶} // Child of parent 1
3 => Person {#314 ▶} // Parent 2 - Single (no relation)
4 => Person {#315 ▶} // Parent 3
5 => Child {#316 ▶} // Child of parent 3
6 => Person {#314 ▶} // Parent 4 - Single (no relation)
我不确定如何执行此操作(Eloquent 或查询生成器)?
我没试过,但我猜这样的东西会起作用:
$c = collect([]);
foreach($people as $person)
{
$children = $person->children;
$c->add($person);
if(count($children) > 0)
{
foreach($children as $child)
{
$c->add($child);
}
}
}
dd($c);