将mysql Query转换为DB :: raw查询

时间:2017-10-20 01:36:23

标签: mysql laravel

有谁知道,如何将此查询转换为原始查询生成器:

SELECT
    A.ID_KANWIL,
    COUNT(A.ID_CABANG) AS CABANG,
    SUM(JUMLAH_KARYAWAN) AS JMLKARYAWAN,
    COALESCE( B.JML_PESERTA, 0 ) AS JMLPESERTA 
FROM ORGANISASI A
    LEFT JOIN (
        SELECT 
            ID_KANWIL,
            SUM(JUMLAH_PESERTA) AS JML_PESERTA 
        FROM CAKUPAN 
        WHERE 
            BULAN=6 
            AND TAHUN=2017 
            AND ID_PROGRAM=1 
        GROUP BY 
            ID_KANWIL,
            ID_PROGRAM
    ) B ON A.ID_KANWIL=B.ID_KANWIL
WHERE 
    A.BULAN=6 
    AND A.TAHUN=2017 
GROUP BY 
    A.ID_KANWIL, 
    A.BULAN, 
    A.TAHUN

我试过这个,

$data=colletc(DB::select( DB::raw("SELECT
    A.ID_KANWIL,
    COUNT(A.ID_CABANG) AS CABANG,
    SUM(JUMLAH_KARYAWAN) AS JMLKARYAWAN,
    COALESCE( B.JML_PESERTA, 0 ) AS JMLPESERTA 
FROM ORGANISASI A
    LEFT JOIN (
        SELECT 
            ID_KANWIL,
            SUM(JUMLAH_PESERTA) AS JML_PESERTA 
        FROM CAKUPAN 
        WHERE 
            BULAN=6 
            AND TAHUN=2017 
            AND ID_PROGRAM=1 
        GROUP BY 
            ID_KANWIL,
            ID_PROGRAM
    ) B ON A.ID_KANWIL=B.ID_KANWIL
WHERE 
    A.BULAN=6 
    AND A.TAHUN=2017 
GROUP BY 
    A.ID_KANWIL, 
    A.BULAN, 
    A.TAHUN") ))->get() 

但我收到了错误

Call to a member function get() on array

2 个答案:

答案 0 :(得分:0)

您在“->get()”功能

上使用colletc

删除 - > get()它应该工作

我建议你使用模型关系,你不需要像你那样进行查询

答案 1 :(得分:0)

试试这个

$data = DB::select(
  "
  SELECT A.ID_KANWIL,
        COUNT(A.ID_CABANG) AS CABANG,
        SUM(JUMLAH_KARYAWAN) AS JMLKARYAWAN,
        COALESCE(B.JML_PESERTA, 0) AS JMLPESERTA
  FROM ORGANISASI A
  LEFT JOIN
    (
     SELECT ID_KANWIL,
            SUM(JUMLAH_PESERTA) AS JML_PESERTA
     FROM CAKUPAN
     WHERE BULAN = :param1
       AND TAHUN = :param2
       AND ID_PROGRAM = 1
     GROUP BY ID_KANWIL,
              ID_PROGRAM
    ) B
    ON A.ID_KANWIL = B.ID_KANWIL
  WHERE A.BULAN = :param3
    AND A.TAHUN = :param4
  GROUP BY A.ID_KANWIL, A.BULAN, A.TAHUN
  ",
  [
    "param1" => $bulan,
    "param2" => $tahun,
    "param3" => $bulan,
    "param4" => $tahun,
]);

此查询是使用命名绑定构建的。您可以阅读更多相关信息here

在查询中,单词:param1将替换为$bulan

的值

:param2已替换为$tahun ...

查询中的

:param1需要将作为第二个参数提供的数组的键与DB::select()匹配(在本例中为"param1" => $bulan,

您需要知道的一件事是,如果您想再次使用相同的$bulan变量,则需要添加:param3的新变量,其值为"bulan3" => $bulan,