Reputation: 79
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();
Upvotes: 4
Views: 35739
Reputation: 219930
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();
Upvotes: 0
Reputation: 1368
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.
Upvotes: 2
Reputation: 787
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.
Upvotes: 19