如何在Laravel中编写联合查询?

时间:2016-06-21 09:37:45

标签: php mysql laravel laravel-5 union

我使用laravel 5.0并且我有mysql查询:

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();

但我没有表现出来。你知道错误在哪里吗?

2 个答案:

答案 0 :(得分:1)

好吧,我终于使用了原始查询..

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

答案 1 :(得分: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