简体   繁体   中英

What is the equivalent of this MySQL query to Laravel Query Builder?

This is my query from MySQL. I want to use 'LEFT JOIN' to two same tables with different aliases and having an 'ON' that has 'AND' inside its parenthesis. And this query arrives with the correct results, but my problem is how can I know the equivalent of this query to its Laravel query?

SELECT * FROM table1 AS a 
LEFT JOIN table1 AS b 
ON (a.column1 = b.column1 AND a.column2 < b.column2)
WHERE b.column2 is null;

And then I use this query in Laravel Query Builder which will query the wrong results.

DB::table('table1 As a')
->leftJoin('table1 As b', 'a.column1', '=', 'b.column1')
->leftJoin('table2 As c','a.column2', '<', 'c.column2')
->whereNull('c.column2')
->get();

This Laravel query is equivalent to this MySQL query which will, unfortunately, query the same wrong results:

SELECT * FROM table1 AS a 
LEFT JOIN table1 AS b 
ON (a.column1 = b.column1 AND )
LEFT JOIN table1 AS c
ON (a.column2 < c.column2)
WHERE b.column2 is null;

You need to pass a function to the leftJoin() Something like this...

DB::table('table1 as a')
    ->leftJoin('table1 as b', function($join) {
        return $join->on('a.column1', '=', 'b.column1')
            ->whereColumn('a.column2', '<', 'b.column2');
    })->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM