如何从Laravel控制器中的5个表编写mysql join子查询

时间:2019-05-23 06:49:02

标签: mysql laravel eloquent laravel-blade query-builder

我有一个像波纹管这样的MySQL查询,我想在laravel控制器中使用它,

我知道如何在laravel中使用join,但是当join语句中还有另一个子查询时,我不知道如何编写

SELECT barangs.id, barangs.kode_barang, barangs.nama_barang, 
IFNULL(a.QTY_IN,0) AS masuk, IFNULL(b.QTY_OUT,0) AS keluar, 
IFNULL(c.PO_RETUR_QTY,0) AS po_retur, IFNULL(d.CUS_RETUR_QTY,0) AS cus_retur, 
barangs.stok AS stok_akhir, barangs.harga_beli
FROM barangs 

LEFT JOIN (
SELECT barang_masuk_detail.id_barang, barang_masuk.tgl_masuk, SUM(barang_masuk_detail.qty_terima) AS QTY_IN
FROM barang_masuk
LEFT JOIN barang_masuk_detail ON barang_masuk.id = barang_masuk_detail.id_brg_masuk
/* WHERE barang_masuk.tgl_masuk BETWEEN "2015-08-01" AND "2015-08-31" */
GROUP BY barang_masuk_detail.id_barang ASC
)AS a ON a.id_barang = barangs.id

LEFT JOIN (
SELECT barang_keluar_detail.id_barang, barang_keluar.tgl_kirim, SUM(barang_keluar_detail.qty_dikirim) AS QTY_OUT
FROM barang_keluar
LEFT JOIN barang_keluar_detail ON barang_keluar.id = barang_keluar_detail.id_brg_keluar
/* WHERE barang_keluar.tgl_kirim BETWEEN "2015-08-01" AND "2015-08-31"*/
GROUP BY barang_keluar_detail.id_barang ASC
)AS b ON b.id_barang = barangs.id

/*join retur try */
LEFT JOIN (
SELECT retur_beli_detail.barang_id, retur_beli.tgl_retur, SUM(retur_beli_detail.retur_qty) AS PO_RETUR_QTY
FROM retur_beli
LEFT JOIN retur_beli_detail ON retur_beli.id = retur_beli_detail.retur_id
/* WHERE retur_beli.tgl_retur BETWEEN "2015-08-01" AND "2015-08-31"*/
GROUP BY retur_beli_detail.barang_id ASC
)AS c ON c.barang_id = barangs.id

/*join retur dari customer */
LEFT JOIN (
SELECT retur_kirim_detail.barang_id, retur_kirim.tgl_retur, SUM(retur_kirim_detail.retur_qty) AS CUS_RETUR_QTY
FROM retur_kirim
LEFT JOIN retur_kirim_detail ON retur_kirim.id = retur_kirim_detail.retur_id
/* WHERE retur_kirim.tgl_retur BETWEEN "2015-08-01" AND "2015-08-31"*/
GROUP BY retur_kirim_detail.barang_id ASC
)AS d ON d.barang_id = barangs.id

如果我在sqlyog中运行,它可以按预期工作,但是不确定如何用laravel语法编写

enter image description here

如果可能,可以根据用户发送的请求在laravel中使用whereBetween对其进行过滤,我需要将语法放在哪里?

like whereBetween([[$ request-> startDate,$ request-> endDate]);

1 个答案:

答案 0 :(得分:1)

使用以下语法执行查询的简单方法:-

DB::select("select * from table JOIN ...");

这将为您提供过滤数据的收集。

修改后的代码

要使用whereBetween() Laravel,您需要在其中编写如下MySQL查询的查询

$startDate = $request->startDate;
$endDate = $request->endDate;

DB::select("
    select * from table JOIN ... 
    where fieldName BETWEEN '$startDate' AND '$endDate'
");

要添加更多条件,我们需要编写纯MySQL查询。