How to use outer full join in laravel 5.0?

2019-07-11 05:14发布

It's my controller :

public function lihatpesanansemua() //ajax
{
    if(Request::ajax())
    {
        $hasil = DB::table('pesanan')->join('pemesan','pemesan.id', '=', 'pesanan.idpemesan')->join('komputer', 'komputer.id' ,'=', 'pesanan.idkomputer')
        ->select('pesanan.id', 'pemesan.nama', 'pesanan.tglpesan', 'pesanan.jampesan', 'pesanan.jamakhir', 'komputer.nama_komputer', 'komputer.lantai', 'komputer.Kelas')
        ->orderby('pesanan.id', 'asc')
        ->get();
        $hasil = json_encode($hasil);
        return $hasil;
    }
}

And that's is inner join. How to change to full outer join ? Thanks, sorry my bad english

1条回答
ゆ 、 Hurt°
2楼-- · 2019-07-11 05:23

I don't know what exactly your query is trying to achieve, and where you need a full outer join, but I will begin this answer by saying that MySQL has no inbuilt support for full outer join. Based on this SO question, we can find a way an alternative way to write the following query:

SELECT * FROM t1
FULL OUTER JOIN t2
    ON t1.id = t2.id

This can be rewritten as a UNION of a left join and a right join:

SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
UNION ALL
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id

In Laravel, we can write the following code to represent the above full outer join:

$second = DB::table('t2')
             ->rightJoin('t1', 't1.id', '=', 't2.id')

$first = DB::table('t1')
            ->leftJoin('t2', 't1.id', '=', 't2.id')
            ->unionAll($first)
            ->get();

Again, I don't know why you think you need two outer joins, but regardless you should be able to adapt the above code and query and use it for your situation.

References:

查看更多
登录 后发表回答