Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.4 subquery in where condition?

I want to write sub query inside where in condition and in subquery were condition, checking with parent query field.

as follows,

$query = DB::table('users');
$query->whereNotIn('users.id', function($query) use ($request) {
            $query->select('award_user.user_id')
                    ->from('award_user')
                    ->where('award_user.user_id', 'users.id')
                    ->where('award_user.award_id', $request->award_id);
        });

Query is working fine, but

 ->where('award_user.user_id', 'users.id')

This line, users.id is not taking from parent query. If I enter manually number, then it is working correctly.

What is wrong with my query.. can you please suggest.

like image 469
Naseeha Sahla Avatar asked Nov 07 '22 19:11

Naseeha Sahla


1 Answers

use whereRaw rather than where

$query = DB::table('users');
$query->whereNotIn('users.id', function($query) use ($request) {
            $query->select('award_user.user_id')
                    ->from('award_user')
                    ->whereRaw('award_user.user_id', 'users.id')
                    ->whereRaw('award_user.award_id = '.$request->award_id);
        });
like image 50
Parth Chavda Avatar answered Nov 14 '22 21:11

Parth Chavda