Laravel 5.4结合两个系列

Jan*_*ose 3 php mysql laravel

所以我有两个系列,salescosts.

现在我需要将它们合并为一个集合以满足我的foreach条件(我不确定我是否可以在一个集合中使用两个集合foreach)

RAW查询:

//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');
Run Code Online (Sandbox Code Playgroud)

这是我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();
Run Code Online (Sandbox Code Playgroud)

我尝试过测试的东西:将集合转换为数组并尝试合并它们但我似乎遇到了问题.

我还原它是因为我不知道这是不是最好的方式.请让我知道最好的方法是什么.

更新:这是这两个查询的输出,希望它有所帮助:

销售

{
    totalSales: "960.00",
    year: 2017
}
Run Code Online (Sandbox Code Playgroud)

成本

{
    totalCost: "792.00",
    year: 2017
}
Run Code Online (Sandbox Code Playgroud)

我尝试了什么:(它说它找不到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);
}
Run Code Online (Sandbox Code Playgroud)

**已解决:**我用过collection merge (不知道有这样的事情)

我使用的语法是,$result = $sales->merge($costs).

这是结果:

{
    totalSales: "960.00",
    year: 2017
},
{
    totalCost: "792.00",
    year: 2017
}
Run Code Online (Sandbox Code Playgroud)

回答者:Sagar Gautam

Sag*_*tam 6

使用收集merge()功能

$result = $sales->merge($costs);
Run Code Online (Sandbox Code Playgroud)

你可以看到文档https://laravel.com/docs/5.4/collections#method-merge