返回孩子在父母之下的记录

时间:2016-10-12 06:18:14

标签: laravel laravel-5 eloquent laravel-query-builder

我正在审核此$people = Person::with('children')->get();之类的模型,这会返回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 ▶}

但是现在我正在尝试将其导出为ex​​cel(Maatwebsite/Laravel-Excel with view)但我需要像这样(他们的父母下的孩子),例如:

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或Query Builder)?

1 个答案:

答案 0 :(得分:1)

我没有尝试,但是这样的事情会起作用我想:

$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);
相关问题