0

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'

2 Answers 2

4

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


    })
Sign up to request clarification or add additional context in comments.

3 Comments

Hi, Thanks for the reply! I have 2 conditions in my letfjoin.. how can I write my both conditions?
You can actually put it in the where statement after the joins, code updated.
The condition should be in the leftjoin , it doesn't show the right result when I place it in where
1

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.