简体   繁体   中英

Implement IF statement in SQL query in Laravel5 eloquent

I want to use this query into my laravel application, but I don't know how to write the IF part!

SELECT    
`users`.* ,    
IF(`friends`.`user_id` = '2' , TRUE , FALSE) AS `user_friend`         
FROM `users`    
LEFT JOIN `friends` ON `friends`.`friend_id` = `users`.`id`  AND `friends`.`user_id` = '2'    
WHERE `users`.`id` != '2'

You can use DB::raw .

User::select(DB::raw('users.* , IF(friends.user_id = '2' , TRUE , FALSE) AS user_friend'))
->join('friends', 'friends.friend_id', '=', 'user.user_id')
->where('friends.user_id, 2)
->where('user.id', '!=', 2);

Updated:

You can have a look at Advanced Join Clauses

->join('friends', function ($join) {
        $join->on('friends', 'friends.friend_id', '=', 'user.user_id')
             ->where('friends.user_id', 2);


    })

Try below full query:

User::select(DB::raw("users.* , IF(friends.user_id = '2' , TRUE , FALSE) AS user_friend"))  
->join('friends', function ($join) {  
  $join->on('friends', 'friends.friend_id', '=', 'user.user_id')  
  ->where('friends.user_id', 2);  
});

This is the version after correction from @SteD answer. Hope this work for you!

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