数据库有一个表records
。这些字段包括product_id
,quantity
,store_id
。
我需要获取属于某个store_id
的行数量的总和,然后才能获得相同的product_id
值。
例如,该表具有值:(2,3,4),(2,1,5),( 1 2,2,4)然后我需要得到总和quantity
以及第1行和第3行的其他列。第二行也将出现在结果中。
我们假设Controller名称为RecordController
,模型名称为Record
。
我该如何撰写查询?
编辑:表格的值为:(2,3,4),(2,1,5),( 1 2,2,4)
答案 0 :(得分:0)
可以使用单个查询完成。
试试这个: -
DB::table('records')
->select('product_id',DB::raw('sum(quantity) as quantity'),'store_id')
->groupBy('product_id')
->groupBy('store_id')
->get();
<强>说明:强>
此查询将获取所有记录和将它们分组为product_id
&amp; store_id
因此,只会为商店中的单个商品获得一行。然后它会在输出中显示sum
quantity
。
<强>更新: - 强>
使用ORM: -
\App\YourModelName::select('product_id',DB::raw('sum(quantity) as quantity'),'store_id')
->groupBy('product_id')
->groupBy('store_id')
->get();
但是你需要在任何情况下编写原始查询,使用默认的ORM功能
无法完成