欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

laravel merge Merging two collection 两个 collection 集合相加 两个 collection 集合合并 并集 有大用

How to merge Eloquent Collections


divdax posted 2 years ago

Hey,

i've two Eloquent Collections with the following collumns:

trackid, title, total (decimal)

and want to merge them. Each Collection has 0, one or multiple items. If a trackid is in two collections i want to add the extra total to the existing item, otherwise just add it.

Any suggestions?

 
T2theC replied 2 years ago

You could look at PHP's array_merge or array_combine (after you have converted the results to arrays) and then convert the output to a Collection if you needed it.

Or better still, I'd probably look at running a raw DB query to get the data you wanted. It sounds to me like the standard Eloquent result sets won't cut it in this case.

If someone else has a solution to merge collections, that might be better. I've not heard of one yet though.

Hope it helps.

monaye replied 1 year ago

you could try to use merger method. http://laravel.com/api/5.1/Illuminate/Database/Eloquent/Collection.html#method_merge

$collection_one->merge($collection_two)

$collection_one->merge($collection_two)

来自 https://laravel.io/forum/10-06-2014-how-to-merge-eloquent-collections

普通分类: