Merging collections

2019-08-07 08:59发布

问题:

I have a raw query:

$data = Product::hydrateRaw(//sql here);

This returns a collection.

I then perform a further query:

$data2 = Product::take(3)->get();

I then wish to merge both collections:

$data->merge($data2);

Unfortunately the merge appears to have no effect, when I dd() the collection only contains $data and not $data2.

Where am I going wrong?

回答1:

Now, when using Product:: you'll get with an Eloquent Collection object which holds your results from using get or any other relationship. The nice thing here is that you can actually choose and customize your Collection, instead of using plain array or something else.

Please read additional details here: http://laravel.com/docs/5.1/eloquent-collections#available-methods. You have a lot of available methods for your Eloquent Collection objects, and one of them is "merge".

Please be carefull that "merge" function does not modify your current Collection $data. Instead of that, it is just returning you merged Collection and that's it.

$mergeData = $data->merge($data2)

If it's still not resolving your needs, feel free to create your Custom Collection and just create a new method there like:

public function merge(Collection $collection) {

    foreach ($collection as $item)
    {
        $this->items[$item->getKey()] = $item;
    }

    //Now this will change your current Collection
}

or use it with an array, and no need of any Hydration

public function merge(array $firstResults) {
    //Do your logic of merging $firstResults with your current collection
}

The thing is that existing "merge" method, accepts only array as a parameter and and the resulted array does not contain any Relationship.

In addition to that, unfortunately Hydrate does not hydrate your Relationship either, so this might be an small or big impediment here.

Other than that, good luck with that.



回答2:

Try this:

$data2 = Product::take(3)->get()->toArray();
$data->merge($data2);

see here.