我在mysql中有这个原始查询,需要翻译成laravel 5.4查询生成器:
SELECT MONTH(calendar.datefield) AS Bulan, calendar.datefield AS Tanggal, IFNULL(SUM(dbk.jumlah),0) AS Jumlah
FROM detail_brg_keluar AS dbk
INNER JOIN penjualan AS pen ON pen.id = dbk.id_brg_keluar
RIGHT JOIN calendar ON (DATE(pen.tgl_keluar) = calendar.datefield)
WHERE
(calendar.datefield BETWEEN
(SELECT MIN(DATE(tgl_keluar)) FROM penjualan AS p
INNER JOIN detail_brg_keluar AS detail ON p.id = detail.id_brg_keluar
WHERE detail.id_produk = 818002)
AND
(SELECT MAX(DATE(tgl_keluar)) FROM penjualan AS pe
INNER JOIN detail_brg_keluar AS det ON pe.id = det.id_brg_keluar
WHERE det.id_produk = 818002))
AND (dbk.id_produk = 818002 OR dbk.id_produk IS NULL)
GROUP BY MONTH(calendar.datefield)
ORDER BY calendar.datefield ASC
这是我的laravel代码,代码错误-_-
$proT = DB::table('detail_brg_keluar AS dbk')
->select( DB::raw('MONTH(calendar.datefield) AS Bulan, calendar.datefield AS Tanggal, IFNULL(SUM(dbk.jumlah),0) AS Jumlah '))
->join('penjualan AS pen', 'pen.id', '=', 'dbk.id_brg_keluar')
->join('calendar', DB::raw('DATE(pen.tgl_keluar)'), '=', 'calendar.datefield')
->whereBetween('calendar.datefield', [$from[0]->tanggalAwal, $to[0]->tanggalAkhir])
->where(DB::raw('dbk.id_produk = 818002 OR dbk.id_produk IS NULL'))
->groupBy(DB::raw('MONTH(calendar.datefield)'))
->orderBy(DB::raw('calendar.datefield', 'ASC'))
->get();
往返的代码:
$from = DB::table('penjualan AS p')
->select(DB::raw('MIN(DATE(tgl_keluar)) AS tanggalAwal'))
->join('detail_brg_keluar AS detail', 'p.id', '=', 'detail.id_brg_keluar')
->where('detail.id_produk', $id)
->get();
$to = DB::table('penjualan AS p')
->select(DB::raw('MAX(DATE(tgl_keluar)) AS tanggalAkhir'))
->join('detail_brg_keluar AS detail', 'p.id', '=', 'detail.id_brg_keluar')
->where('detail.id_produk', $id)
->get();
我不知道了吗?
全部感谢
答案 0 :(得分:1)
使用此:
$from = DB::table('penjualan AS p')
->select(DB::raw('MIN(DATE(tgl_keluar)) AS tanggalAwal'))
->join('detail_brg_keluar AS detail', 'p.id', '=', 'detail.id_brg_keluar')
->where('detail.id_produk', $id);
$to = DB::table('penjualan AS p')
->select(DB::raw('MAX(DATE(tgl_keluar)) AS tanggalAkhir'))
->join('detail_brg_keluar AS detail', 'p.id', '=', 'detail.id_brg_keluar')
->where('detail.id_produk', $id);
$proT = DB::table('detail_brg_keluar AS dbk')
->select( DB::raw('MONTH(calendar.datefield) AS Bulan, calendar.datefield AS Tanggal, IFNULL(SUM(dbk.jumlah),0) AS Jumlah '))
->join('penjualan AS pen', 'pen.id', '=', 'dbk.id_brg_keluar')
->rightJoin('calendar', DB::raw('DATE(pen.tgl_keluar)'), '=', 'calendar.datefield')
->whereRaw('calendar.datefield BETWEEN ('.$from->toSql().') AND ('.$to->toSql().')', [$id, $id])
->where(function($query) {
$query->where('dbk.id_produk', 818002)->orWhereNull('dbk.id_produk');
})
->groupBy(DB::raw('MONTH(calendar.datefield)'))
->orderBy('calendar.datefield', 'ASC')
->get();
$from
和$to
,请使用生成的SQL。->join('calendar'
替换为->rightJoin('calendar'
。where(DB::raw())
。orderBy()
不需要原始表达式。