laravel 合并集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30779075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Merging collections
提问by panthro
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.
不幸的是,合并似乎没有效果,当我 dd() 集合只包含 $data 而不是 $data2 时。
Where am I going wrong?
我哪里错了?
回答by Kun Andrei
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.
现在,当使用 Product:: 时,您将获得一个 Eloquent Collection 对象,该对象保存使用 get 或任何其他关系的结果。这里的好处是您实际上可以选择和自定义您的 Collection,而不是使用普通数组或其他东西。
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".
请在此处阅读更多详细信息:http: //laravel.com/docs/5.1/eloquent-collections#available-methods。你的 Eloquent Collection 对象有很多可用的方法,其中之一是“合并”。
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.
请注意“合并”功能不会修改您当前的 Collection $data。取而代之的是,它只是返回您合并的集合,仅此而已。
$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.
除此之外,不幸的是,Hydrate 也不会滋润你的关系,所以这可能是一个或大或小的障碍。
Other than that, good luck with that.
除此之外,祝你好运。