首先,我对每天销售的产品进行统计时遇到了问题。在sql中,我有查询
select product_name, sum(quantity) as quantity from invoice_product 
join invoices on invoices.id = invoice_product.invoice_id
join products on products.id = invoice_product.product_id
 where invoices.issued_at = '2019-05-16' 
 and products.`made_by_us` = 1
 group by product_name它向我展示了我感兴趣信息,但是我使用product_name来制作group by,但是我应该使用product_id -我也需要显示名称,但是我不知道怎么做。
其次,我想在Laravel中使用它,所以也许有人知道用Eloquent可以做到这一点?
提前感谢您:)
发布于 2019-05-17 04:31:51
我会将withCount()与select(DB::raw())结合使用,如下所示:
$products = Product::withCount(['invoices as quantity' => function ($query) {
    $query->select(DB::raw('sum(quantity)'));
}])->get();然后,您可以像这样访问每个数量总和:
$quantity = $products->first()->quantity;https://stackoverflow.com/questions/56172447
复制相似问题