欢迎各位兄弟 发布技术文章
这里的技术是共享的
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?
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.
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