How to join a subqueries during leftjoin using query builder laravel?

2k Views Asked by At
$productLists = DB::table('A')
                    ->leftJoin('B', function($join) {
                        $join->where('B.qty','=', 1);
                        $join->on("B.id", "=", "A.id");
                    })
                    ->select('A.*','B.*')
                    ->get();

What's wrong with the query?

The field I get from B table all returned null .

Am I doing it in wrong way?

3

There are 3 best solutions below

0
On
$productLists = DB::table('A') ->select('A.*','B.*')->join('B','B.id','=','A.id')->where('B.qty', 1) ->get();

this is one way to write joins in laravel..

0
On

try this:

$productLists = DB::table('A')
                  ->join('B', 'B.id', '=', 'A.id')
                  ->select('A.*','B.*')
                  ->where('B.qty','=', 1)
                  ->get();
1
On

Try this:

$productLists = DB::table('A')
               ->leftJoin('B', function($join) {
                      $join->where('B.qty','=', 1)
                           ->on("B.id", "=", "A.id");
               })
               ->select('A.*','B.*')
               ->get();