Salar
Salar

Reputation: 5509

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') ;

Upvotes: 5

Views: 8377

Answers (1)

Pouya Khalilzad
Pouya Khalilzad

Reputation: 1787

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') ;
            });

Upvotes: 15

Related Questions