合并收藏 [英] Merging collections

查看:110
本文介绍了合并收藏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个原始查询:

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

这将返回一个集合。

然后进一步查询:

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

然后我希望合并这两个集合:

I then wish to merge both collections:

$data->merge($data2);

不幸的是,合并似乎没有任何效果,当我的dd()集合只包含$数据和不是$ data2。

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

我在哪里出错?

推荐答案

现在,当使用Product ::时,你会得到一个强大的Collection对象,它使用get或任何其他关系来保存你的结果。这里的好处是您可以实际选择和自定义您的集合,而不是使用纯数组或其他内容。

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.

请阅读其他详细信息:http://laravel.com/docs/5.1/eloquent-collections#available-methods 。你有很多可用的方法,用于您的雄辩收藏对象,其中一个是合并。

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".

请谨慎,合并功能不修改您当前的Collection $数据。而不是这样,它只是返回你合并的集合,就是这样。

$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.

除此之外,祝你好运。

这篇关于合并收藏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆