Laravel 5.4查询生成器SUM()来自两个不同的表

I'm having problems getting the SUM of a certain field from two tables.

So to start things off, here's my query.

        //Getting of Cost of Goods Sold (Menus)
        $totalMenuCost = DB::raw('(SUM(orders.qty * orders.cost)) as cost');
        $yearMenuSold = DB::raw('YEAR(orders.created_at) as year');

        $menuscost =  DB::table('orders')
            ->where('status', 'served')
            ->select($totalMenuCost, $yearMenuSold);

        //Getting of Cost of Goods Sold (Items)
        $totalItemCost = DB::raw('(SUM(purchases.qty * purchases.cost)) as cost');
        $yearItemSold = DB::raw('YEAR(purchases.created_at) as year');

        $itemcost =  DB::table('purchases')
            ->where('status', 'served')
            ->union($menuscost)
            ->select($totalItemCost, $yearItemSold)
            ->get();

And when I try to do return $itemcost. It returns two rows:

[
  {
    cost: "792.00",
    year: 2017
  },

  {
    cost: "1700.00",
    year: 2017
  }
]

I'm trying to make it return a single row but having it added, like this:

[
  {
    cost: "2492.00", // that's 1,700 + 792
    year: 2017
  }
]
$itemcost =  DB::table('purchases')
            ->where('status', 'served')
            ->union($menuscost)
            ->select($totalItemCost, $yearItemSold)
            ->get();

In your Example you are just selecting $totalItemCost, $yearItemSold and union from other table ($menuscost).

So that won't add up the results.

///////////Try Changing your Query in this Format

select column1,sum(column2) total
from
(
    select column1,column2
    from Table1
    union all
    select column1,column2
    from Table2
) t
group by column1

Hope this Helps.. Let me know if more help is needed.

All seems okay, Have you changed your $itemcost like this

$itemcost =  DB::table('purchases')
             ->where('status', 'served')
             ->select($totalItemCost, $yearItemSold)
             ->union($menuscost)
             ->groupBy('year')
             ->get();

UPDATE

Since above not working for your case,

I think problem on group by is with union so Have a new try with this one.

$menuscost =  DB::table('orders')
        ->where('status', 'served')
        ->select($totalMenuCost, $yearMenuSold)
        ->groupBy('year');

$itemcost =  DB::table('purchases')
             ->where('status', 'served')
             ->select($totalItemCost, $yearItemSold)
             ->groupBy('year')
             ->union($menuscost)
             ->groupBy('year')
             ->get();

If this is not working then can you add output of this query.