Home > front end >  Laravel leftJoin returns null from 2nd table
Laravel leftJoin returns null from 2nd table

Time:07-27

I have 2 table duty_sheets

centerId | centerName | p1 | p2 | p3 | p4 | ...p22 | examiId
   1     |  xyz       |  1 |  5 |  8 |  7 |    1   |   1
   2     |  abc       |  9 |  1 |  6 |  6 |    1   |   1

and feedback

id | centerId | inspectorId | A  | B | C | examiId
 1 |    1     |     1       |  1 | 5 | 8 |   1
 2 |    2     |     9       |  9 | 1 | 6 |   1

here is my code

$center = DutySheet::select('duty_sheets.centerId', 'duty_sheets.centerName','feedback.id')
        ->leftJoin('feedback', function ($leftJoin) {
        $leftJoin->on('duty_sheets.examId', 'feedback.examId')
            ->where("duty_sheets.centerId", 'feedback.centerId')
            ->where("feedback.inspectorId", 1);
    })
        ->where("duty_sheets.examId", 1)
        ->where("p20", 1)
        ->get();
    dd($center);

to retrieve "All rows from DutySheet where p20 = 1 and dutysheet.examId = 1, and relevant rows from feedback depend on centerId, inspectorId and examId.

The problem is that the query return feedback.id as null while the record exist in feedback table with the ids.

Laravel version = 9

CodePudding user response:

The problem is in left Join

->where("duty_sheets.centerId", 'feedback.centerId')

This build a where against the value 'feedback.centerId'

duty_sheets.centerId='feedback.centerId' 

You need use

   ->on("duty_sheets.centerId",'=', 'feedback.centerId')

Or

 ->whereColumn("duty_sheets.centerId", 'feedback.centerId')
       
  • Related