2015-09-04 33 views
8

複数のコレクションを1つにマージしたい。Laravelで複数のコレクションを正しくマージする方法

$allItems = $collection1->merge($collection2) 
         ->merge($collection3) 
         ->merge($collection4) 
         ->merge($collection5); 

これは、実際に作業を行いますが、私はいくつか、またはコレクションのすべてが何のオブジェクトが含まれていない場合に問題に実行:私は、次のされたソリューションを、持っています。 call to merge() on non objectの行に誤りがあります。

その有効性を確認しながら、私は実際には、コレクションのすべての配列を作成し、それらを反復処理しようとしたが、それはうまくいきませんでしたし、私はそれは非常にエレガントではなかった気がします。コレクションの一部または全部が空または無効である可能性がありますことを考慮しながら、私はエレガントに、複数のコレクションをマージするこのプロセスを反復処理するにはどうすればよい

?感謝!

答えて

11

私がやったことは、各ステップを分けることでした。コレクションの一部またはすべてが無効だった可能性があるので、それを殺していたのはマージ連鎖でした。

$allItems = new \Illuminate\Database\Eloquent\Collection; //Create empty collection which we know has the merge() method 
$allItems = $allItems->merge($collection1); 
$allItems = $allItems->merge($collection2); 
$allItems = $allItems->merge($collection3); 
$allItems = $allItems->merge($collection4); 
+1

これは連鎖できないのは変ですが、これが正しいことを確認できます。 – mopo922

+2

これを見ている人のためだけに、 '$ allItems = collect();'を実行して新しいコレクションを作成することができます。 –

0

コレクションが実際にnullまたはPHPのサポートであれば、それはあなたが行うことができ、あなたのデータに依存:

$allItems = $collection1->merge($collection2 ?: collect()) 
        ->merge($collection3 ?: collect()) 
        ->merge($collection4 ?: collect()) 
        ->merge($collection5 ?: collect()); 

か、減らすやりたい:

$allItems = collect([$collection2, $collection3, $collection4])->reduce(function($arr, $item) { 
     if (empty($item) || $item->isEmpty()) 
      return $arr; 
     return $arr->merge($item); 
    }, $collection1); 

またはプレーンなPHPなし削減をオーバーヘッド

$allItems = array_reduce([ 
     $collection2, 
     $collection3, 
     $collection4 
    ], function($arr, $item) { 
     if (empty($item) || $item->isEmpty()) 
      return $arr; 
     return $arr->merge($item); 
    }, $collection1); 
+0

残念ながら、これらは$をincluing、考慮にコレクションの一部またはすべてが無効である可能性という事実を取ることはありませんcollection1 – Marcel

1

私は同じ質問を持っていたので、私は、次の方法でそれを解決:

$clients = ClientAccount::query()->get(); 
$admins = AdminAccount::query()->get(); 

$users = collect($clients)->merge($admins)->merge($anotherCollection)->merge(...); 
関連する問題