Laravel 5.4 合并两个集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45580603/
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
Laravel 5.4 Combining two collections
提问by Jan Ariel San Jose
So I Have two collections, sales
and costs
.
所以我有两个集合,sales
和costs
.
Now I need them to combine into one collection for my foreach
condition (I'm not sure if I can use two collections in one foreach
)
现在我需要根据我的foreach
情况将它们组合成一个集合(我不确定是否可以将两个集合合二为一)foreach
RAW Queries:
原始查询:
//Raw MySQL Queries for Sales
$total_sales = DB::raw('SUM(receipts.total) as totalSales');
$year_receipt_created = DB::raw('YEAR(receipts.created_at) as year');
//Raw MyQSL Queries for Cost of Goods Sold
$total_cost = DB::raw('(SUM(qty * cost)) as totalCost');
$year_sold = DB::raw('YEAR(created_at) as year');
Here's my query
for these two collections
:
这是我query
的这两个collections
:
$sales = DB::table('receipts')
->where('status', 'served')
->where('mode', 'restaurant')
->select($total_sales, $year_receipt_created)
->groupBy('year')
->get();
$costs = DB::table('orders')
->where('status', 'served')
->select($total_cost, $year_sold)
->groupBy('year')
->get();
Things I've tried testing:Converting the collections into array and tried merging them but I seem to have problems.
我尝试过的测试:将集合转换为数组并尝试合并它们,但我似乎遇到了问题。
I reverted it because I don't know if it's the best way or not. Please let me know what's the best way.
我恢复了它,因为我不知道这是否是最好的方法。请让我知道什么是最好的方法。
UPDATE:Here's the output for those two queries, hope it helps:
更新:这是这两个查询的输出,希望它有所帮助:
Sales
销售量
{
totalSales: "960.00",
year: 2017
}
Costs
费用
{
totalCost: "792.00",
year: 2017
}
What I tried: (It says it cannot find totalCost)
我试过的:(它说它找不到总成本)
//Combining TWO collections into ONE Array
$gross_profit = array();
foreach (array_merge($sales, $costs) as $data)
{
$keys = array('total_sales', 'total_cost', '$year');
$values = array($data->totalSales, $data->totalCost, $data->year);
$gross_profit[$data] = array_combine($keys, $values);
}
**SOLVED: ** I used collection merge
(didn't knew there was such a thing)
**解决:**我用过collection merge
(不知道有这样的东西)
The syntax I used is, $result = $sales->merge($costs)
.
我使用的语法是,$result = $sales->merge($costs)
。
Here's the result:
结果如下:
{
totalSales: "960.00",
year: 2017
},
{
totalCost: "792.00",
year: 2017
}
Answered by: Sagar Gautam
回答者:萨加尔·高塔姆
回答by Sagar Gautam
Use collection merge()
function like
使用收集merge()
功能,如
$result = $sales->merge($costs);
You can see docs https://laravel.com/docs/5.4/collections#method-merge
您可以查看文档https://laravel.com/docs/5.4/collections#method-merge