如何在Laravel中正确合并多个集合

时间:2015-09-04 00:51:13

标签: php laravel laravel-4 foreach laravel-5

我想将多个集合合并为一个。我有一个解决方案,其中包括:

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

这确实有效,但在部分或全部集合中不包含任何对象的情况下,我遇到了问题。我在call to merge() on non object

的行中出现了错误

我实际上试图创建一个包含所有集合的数组,然后迭代它们,同时检查它们的有效性,但它不起作用,我觉得它不是很优雅。

如何考虑到部分或全部集合可能为空或无效,我如何优雅地迭代这个合并多个集合的过程?不胜感激!

6 个答案:

答案 0 :(得分:19)

我最终做的是分离每一步。合并链是杀死它的,因为部分或全部集合可能都是无效的。

$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 :(得分:3)

我有同样的问题,所以我通过以下方式解决了这个问题:

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

$users = collect($clients)->merge($admins)->merge($anotherCollection)->merge(...);

答案 2 :(得分:1)

取决于你的数据,如果集合实际上是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);

答案 3 :(得分:1)

我使用了set spark.sql.files.maxRecordsPerFile = 100 ,但是遇到了一个小问题。因此,我添加此内容是为了防止其他人遇到相同的问题。 ->merge()是一种更好的数据库集合合并解决方案。

->concat()

这样做的原因是在合并时,它们以表的 ID 作为键。因此,如果两个表有两个具有相同表ID $allItems = new \Illuminate\Database\Eloquent\Collection; $allItems = $allItems->concat($collection1); $allItems = $allItems->concat($collection2); 的记录,则只会向->merge()添加一个记录。但是$allItems将按原样添加两条记录。

答案 4 :(得分:0)

您也可以尝试:

$allItems = collect([
  'collection_1_key' => $collection_1,
  'collection_2_key' => $collection_2,
  'collection_3_key' => $collection_3,
  'collection_4_key' => $collection_4,
]);

答案 5 :(得分:0)

只需使用 merge

$items  = Model0::get();
$items1 = Model1::get();
$items2 = Model2::get();
$items3 = Model3::get();


$items = $items->merge($items1);
$items = $allItems->merge($items2);
$items = $allItems->merge($items3);

这也可以很简单在一行中

$items = $items->merge($items1)->merge($items2)->merge($items3);

dd($items);

它将合并您的所有收藏...

相关问题