Mounir Elfassi Mounir Elfassi - 6 months ago 33
SQL Question

"IN" query in Laravel 5.2

i'm trying to get this query :

$my_query = "select * from tableuser where `userid`<> '$userid' and userid in
(select friend from userrelations where blocked='no' and user_id='$userid')";


to work in
Laravel 5.2


what i tried so far :

$query_first = DB::table('userrelations')
->select('friend')
->where('blocked' , '=', 'no')
->where('user_id' , '=', $userid)
->get();

$my_query = DB::table('tableuser')
->select('*')
->where('userid' , '<>', $userid)
->where('userid' , 'in', $query_first)
->get();


by doing this i get empty result, which is not correct.

any help please?

Answer

For first query you should replace

->get();

with

->pluck('id');

With pluck() you'll get an array of ids instead of array of objects.


Then, incorrect part in second query:

->where('userid' , 'in', $query_first)

There's whereIn():

$users = DB::table('tableuser')->whereIn('userid', $query_first)->get();