2016-06-21 75 views
2

我使用laravel 5.0和我有MySQL查詢:如何在Laravel中編寫聯合查詢?

SELECT surat_masuk.id_surat, 
     surat_masuk.nomor_surat 
FROM surat_masuk 
WHERE ! EXISTS (SELECT * 
       FROM file_replace 
       WHERE id_surat_lama = surat_masuk.id_surat) 
     AND surat_masuk.id_jenis_surat = '6' 
     AND surat_masuk.deleted = '0' 
UNION 
SELECT id_surat_lama 
FROM file_replace 
WHERE id_surat_baru = '38' 

而且我寫的,在我的laravel代碼爲:

$nomor_surat1 = DB::table('surat_masuk')->select('id_surat', 'nomor_surat') 
    ->where('id_jenis_surat', '=', $id_jenis_surat) 
    ->where(function ($query) { 
     $query->where('masa_berlaku_to', '>=', date('Y-m-d')) 
      ->orwhere('masa_berlaku_to', '=', '0000-00-00'); 
    }) 
    ->whereExists(function ($query) { 
     $query 
      ->from('file_replace') 
      ->where('id_surat_lama', '==', 'surat_masuk.id_surat'); 
    }) 
    ->where('deleted', '=', '0'); 

$nomor_surat = DB::table('file_replace')->join('surat_masuk', 'file_replace.id_surat_lama', '=', 'surat_masuk.id_surat') 
    ->select('id_surat_lama', 'nomor_surat') 
    ->where('id_surat_baru', '=', $id_surat_baru) 
    ->union($nomor_surat1)->get(); 

但我已經沒有什麼表現。你知道錯誤在哪裏嗎?

+1

您是否嘗試過'DB ::選擇()' ?只需在裏面放入原始的SQL查詢,你就可以走了。 – linuxartisan

回答

1

好了,我終於用原始查詢..

$results = DB::select(DB::raw("SELECT * FROM some_table WHERE some_col = '$someVariable'"));

+3

你也可以嘗試DB :: select('SELECT * FROM some_table WHERE some_col =?',[$ someVariable]);以避免安全風險 – rypskar

+0

OP實際上應該執行@rypskar建議的操作。 – linuxartisan

0

請參閱答案,這可能會幫助你..

SELECT surat_masuk.id_surat, 
     surat_masuk.nomor_surat 
FROM surat_masuk 
WHERE ! EXISTS (SELECT * 
       FROM file_replace 
       WHERE id_surat_lama = surat_masuk.id_surat) 
     AND surat_masuk.id_jenis_surat = '6' 
     AND surat_masuk.deleted = '0' 
UNION 
SELECT id_surat_lama 
FROM file_replace 
WHERE id_surat_baru = '38' 

//converted to laravel elequent query. 

$first_sql=DB::table('surat_masuk as sm1') 
      ->whereNotExists(function($query) { 
       $query->from('file_replace as fr1') 
       ->where('fr1.id_surat_lama','sm1.id_surat'); 
      })->where('sm1.id_jenis_surat',6) 
      ->where('sm1.deleted',0) 
      ->select('sm1.id_surat', 'sm1.nomor_surat'); 
    //will return an elequent object, append '->get()' to see the output seperately 
$actual_result=DB::table('file_replace as fr2') 
       ->where('fr2.id_surat_baru',38) 
       ->select('fr2.id_surat_lama') 
       ->union($first_sql) 
       ->get(); 
    //will return an array of result set