[英]Laravel group by id, sum qty and group date to month and year request only and get count
我想根據 2 個組制作數據。 即當年的月份組和組id然后根據產品的現有產品id計算
我試過這段代碼
$tahunx = '2021';
$barangmasuk=BarangMasuk::groupBy('id_barang','months')->select([
'barang_masuk.id_barang',
DB::raw("DATE_FORMAT(tgl_masuk,'%M %Y') as months", '=',$tahunx),
DB::raw('sum(jml_bm) as jumlah')
])->get();
dd($barangmasuk);
我想創建看起來像這樣的數據
我使用的是表 1 和表 2
我已經給出了,但這是結果,按 id_barang 分組可以,但按月份分組沒有得到結果
Collection {#862 ▼
#items: array:7 [▼
0 => BarangMasuk {#854 ▼
#table: "barang_masuk"
#fillable: array:4 [▶]
#connection: "mysql"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:3 [▼
"id_barang" => 1
"months" => "April 2021"
"jumlah" => "100"
]
#original: array:3 [▼
"id_barang" => 1
"months" => "April 2021"
"jumlah" => "100"
]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
1 => BarangMasuk {#855 ▶}
2 => BarangMasuk {#856 ▶}
3 => BarangMasuk {#857 ▶}
4 => BarangMasuk {#858 ▶}
5 => BarangMasuk {#859 ▶}
6 => BarangMasuk {#860 ▶}
]
}
結果是雙id和月份數據
然后這是我使用的表的示例
塔貝爾巴朗
+-----+-------------+---------+
| id | nama_barang | stok |
+-----+-------------+---------+
| 1 | Sayur | 10 |
| 2 | daging | 50 |
| 3 | Buah | 20 |
+-----+-------------+---------+
塔貝爾巴朗馬蘇克
+-----+-------------+-----------+---------+
| id | tgl_masuk | id_barang | jml_bm |
+-----+-------------+-----------+---------+
| 1 | 25-05-2021 | 1 | 200 |
| 2 | 25-05-2021 | 2 | 100 |
| 3 | 25-05-2021 | 1 | 100 |
| 4 | 25-05-2021 | 1 | 200 |
| 5 | 25-05-2021 | 2 | 100 |
| 6 | 25-05-2021 | 1 | 100 |
| 7 | 25-04-2021 | 1 | 300 |
| 8 | 25-04-2021 | 2 | 200 |
| 9 | 25-04-2021 | 2 | 100 |
| 10 | 25-04-2021 | 1 | 200 |
| 11 | 25-04-2021 | 3 | 100 |
| 12 | 25-04-2021 | 3 | 100 |
+-----+-------------+-----------+---------+
為了得到這樣的結果
+-------------+------------+-----------+
| tgl_masuk | id_barang | sum(jml_bm|
+-------------+------------+-----------+
| April-2021 | 1 | 500 |
| April-2021 | 2 | 300 |
| April-2021 | 3 | 200 |
| Mei-2021 | 1 | 600 |
| Mei-2021 | 2 | 200 |
+-------------+------------+-----------+
在普通的 MySQL 查詢中,您可以執行以下操作:
SELECT DATE_FORMAT(tgl_masuk,'%M-%Y') AS 'DY', id_barang, SUM(jml_bm) AS 'Jumlah'
FROM barang_masuk
WHERE YEAR(tgl_masuk)='2021'
GROUP BY DY, id_barang
ORDER BY DY, id_barang;
雖然我不確定如何將此查詢轉換為 laravel/eloquent。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.