如何按 storage_id 和 product_id 总结 table 行
How to sum up table rows group by storage_id and product_id
我正在尝试解决以下问题:我首先共享 table 图像(从那里汇总行)
当api命中时,应该先对storage_id
进行分组,然后对product_id
进行分组,然后对相同的product_id
[=进行汇总quanitity
24=]
例如:
有两个 storage_id
: 1 & 2 ,两个不同的 product_id
: 1 & 2 。现在输出应该是 sum all the rows where storage_id, where product_id
。应该有 3 JSON 个输出,用于存储 1 和产品 1,用于存储 1 和产品 2。用于存储 2 和产品 2。然后它们应该存储在 table 中,如下所示 table
到目前为止我的代码(来自控制器):
$storages = Storage::get(); // getting storage list
foreach($storages as $storage => $val){
$storage_id[] = $storages[$storage]->id; // Getting array of id only
$get_storage[] = Storage::with('storageProducts')->whereIn('id', $storage_id)->get();
foreach($get_storage as $product => $val){
foreach($val as $d){
$a[$d->id] = StorageProduct::where('transfer_type',1)
->where('storage_id',$d->id)
->groupBy('storage_id', 'product_id')
->sum('quantity');
}
}
}
我得到的输出:
{
"1": 28,
"2": 23
}
SELECT storage_id , product_id ,SUM(stock) as stock FROM tb_stock
GROUP BY product_id , storage_id
$result = StorageProduct::where('transfer_type',1)
->select('storage_id', 'product_id', DB::raw('SUM(quantity) as stock'))
->groupBy('storage_id', 'product_id')
->get();
我正在尝试解决以下问题:我首先共享 table 图像(从那里汇总行)
当api命中时,应该先对storage_id
进行分组,然后对product_id
进行分组,然后对相同的product_id
[=进行汇总quanitity
24=]
例如:
有两个 storage_id
: 1 & 2 ,两个不同的 product_id
: 1 & 2 。现在输出应该是 sum all the rows where storage_id, where product_id
。应该有 3 JSON 个输出,用于存储 1 和产品 1,用于存储 1 和产品 2。用于存储 2 和产品 2。然后它们应该存储在 table 中,如下所示 table
到目前为止我的代码(来自控制器):
$storages = Storage::get(); // getting storage list
foreach($storages as $storage => $val){
$storage_id[] = $storages[$storage]->id; // Getting array of id only
$get_storage[] = Storage::with('storageProducts')->whereIn('id', $storage_id)->get();
foreach($get_storage as $product => $val){
foreach($val as $d){
$a[$d->id] = StorageProduct::where('transfer_type',1)
->where('storage_id',$d->id)
->groupBy('storage_id', 'product_id')
->sum('quantity');
}
}
}
我得到的输出:
{
"1": 28,
"2": 23
}
SELECT storage_id , product_id ,SUM(stock) as stock FROM tb_stock
GROUP BY product_id , storage_id
$result = StorageProduct::where('transfer_type',1)
->select('storage_id', 'product_id', DB::raw('SUM(quantity) as stock'))
->groupBy('storage_id', 'product_id')
->get();