雄辩的-合并两个具有汇总/总和的查询结果

时间:2019-02-14 13:16:10

标签: php laravel eloquent

我已经尝试了几个小时才能做到这一点,但可以提供一些帮助。我有以下2个查询,它们对同一模型上的列求和,但是总和之一需要一个where条件。

在SQL中,我认为这将是一个相对简单的子选择,但是我无法让它雄辩地工作。

public function receivedContents() : Collection
{
    return $this->stockMovements()
        ->with('product')
        ->groupBy('product_id')
        ->where(function($query){
            $query->where('action', 'receive')->orWhere('action', 'void_receive');
        })
        ->get([DB::raw('SUM(received) as received_qty'), 'product_id']);
}

public function liveContents() : Collection
{
    return $this->stockMovements()
        ->with('product')
        ->groupBy('product_id')
        ->get([DB::raw('SUM(received) + SUM(processed) as live_qty'), 'product_id']);
}

我正在寻找以下结果:

  • product_id
  • received_qty(接收到的动作总数或void_received接收到的总数)
  • live_qty(简单的总和或已接收+处理的列)

理想情况下,我想将其保存在一个雄辩的集合中,以便仍然可以访问模型关系。

任何帮助将不胜感激!

0 个答案:

没有答案