How to use outer full join in laravel 5.0?

2019-07-11 04:46发布

问题:

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:

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:

  • Link to full outer joins in MySQL: Full Outer Join in MySQL
  • Link to Laravel 5.3 query builder docs: https://laravel.com/docs/5.3/