Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Left join add where clause to right table

If I add a where clause to a left join, that this where clause is working on the right table, I only get those results frome left table that can match the right table.

$notifications = \DB::table('notifications')
            ->select(\DB::raw("notifications.uuid ,images.local_path as title_image" ))
            ->leftJoin('images','images.owner_uuid', '=' ,'notifications.uuid')
where('images.relation','=','notification_title') ;

How can I add this where clause to the left join, that does not make this problem?

where('images.relation','=','notification_title') ;
like image 606
Salar Avatar asked May 30 '16 06:05

Salar


1 Answers

in left join all the where clauses that are going to act on the right table must be added to the JOIN statement itself. use this code

$notifications = \DB::table('notifications')
            ->select(\DB::raw("notifications.uuid , images.local_path as title_image" ))
            ->leftJoin('images',function ($join) {
                $join->on('images.owner_uuid', '=' , 'notifications.uuid') ;
                $join->where('images.relation','=','notification_title') ;
            });
like image 98
Pouya Khalilzad Avatar answered Nov 12 '22 03:11

Pouya Khalilzad