2017-10-20 45 views
1

沒有人知道,如何轉換此查詢原始的QueryBuilder:轉換MySQL查詢到DB ::原始查詢

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 

回答

0

您在「colletc」功能上使用->get()

刪除 - > get()方法它應該工作

我建議你使用該模型的關係,你不需要像你一樣

+0

謝謝@peter,我已經替換 - > get()與所有(),那是工作完美。 –

0

使querys試試這個

$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將與$tahun取代的$bulan

:param2值替換...

:param1查詢需要匹配陣列的關鍵作爲第二個參數提供給DB::select()(在這種情況下爲"param1" => $bulan,

你需要知道的一件事是如果你想使用相同的$bulan v易再次,你需要添加新的:param3將獲得值"bulan3" => $bulan,

+0

非常感謝你,我得到錯誤,..我給DB :: Raw(befor db :: select)。並且工作正常 –

+0

當你使用'DB :: raw()'的時候要特別小心,尤其是當你在查詢中傳遞變量時(例如'$ bulan')。這可能會讓你打開[sql注入](https://stackoverflow.com/questions/601300/what-is-sql-injection)。這就是爲什麼我提供了使用**命名綁定** – ljubadr

+0

的解決方案,您是否添加了'DB :: select(DB :: raw(「query ....」))?如果是,我會更新答案。 – ljubadr