4

I wanted to pass all $id values to the where clause, 3rd line from the code below. but as i'am trying to return $friend it is null. am i addressing the $id values incorrectly? or i got it wrong in the query? i checked my database and it should return 2 rows.

i also checked $id by returning it and it returns what i am expecting and i guess i got it wrong in the query in $friend line.

$x = user->id;  

$id = DB::table('requests')->select('id')->where('id', '=', $x)->get();

$friend = DB::table('users')->where('id', 'in', $id)->get();

3 Answers 3

19

You need to use whereIn(), and maybe a better option for the whole deal would be:

$ids = DB::table('requests')->where('id', $x)->lists('id');
$friend = DB::table('users')->whereIn('id', $ids)->get();

Note that the second parameter of whereIn() needs to be an array.

1
  • thnx dude. this really helped me. Oct 7, 2015 at 16:55
1

What you want is whereIn (scroll down a bit). It's also possible to use whereNotIn.

$userIds = [1, 2, 3];
$friend = DB::table('users')->whereIn('id', $userIds)->get();

Or whereNotIn:

$userIds = [1, 2, 3];
$friend = DB::table('users')->whereIn('id', $userIds)->get();

Take a look at all the possible advanced where clauses which are supported by the Laravel query builder.

0

You can do it all in a single query:

$friends = DB::table('users')->whereIn('id', function ($query) use ($user) {
    $query->select('id')->from('requests')->where('id', $user->id);
})->get();
4
  • I believe that's still 2 queries, just nested. Oct 7, 2015 at 20:22
  • @YasenSlavov - Nope. It's a subquery: select * from users where id in (select id from requests where id = ?) Oct 7, 2015 at 20:25
  • That's what I meant. But they're still considered separate queries performance-wise. Oct 7, 2015 at 21:03
  • 2
    Nope. There's a huge difference. This is a single trip to the database. Oct 7, 2015 at 21:09

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.