我正在嘗試以下問題:我首先共享表格影像(從哪里總結行)

當 api 被命中時,它應該先分組storage_id,product_id然后總結quanitity相同product_id
例如 :
有兩個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。然后它們應該存盤在如下表所示的表中

到目前為止我的代碼(來自控制器):
$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
}
uj5u.com熱心網友回復:
$result = StorageProduct::where('transfer_type',1)
->select('storage_id', 'product_id', DB::raw('SUM(quantity) as stock'))
->groupBy('storage_id', 'product_id')
->get();
uj5u.com熱心網友回復:
SELECT storage_id , product_id ,SUM(stock) as stock FROM tb_stock GROUP BY product_id , storage_id
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/477005.html
上一篇:控制器已匯入,但web.php拋出目標類[App\Http\Controllers\Auth\LoginController]不存在
下一篇:插入新的資料庫表行后立即更新表
