简体   繁体   中英

How to use alias for whereIn in laravel

Im trying to use whereIn() method in laravel 5.2 but suddenly it returns a column not found error .

Controller

$users = \App\User::select([
    DB::raw('(CASE WHEN users.id < 4 THEN users.id ELSE "" END) as user_id')
]);

$users->whereIn('user_id', [1,2,3]);

return $users->get();

Error

Column not found: 1054 Unknown column 'user_id'

the whereIn can be apply only on a column, since you do not have that column, simply make it!

you can do this using sub query then join it :

 $query1 = $users = \App\Models\User::select([
            DB::raw('users.id as id_to_join,(CASE WHEN users.id < 4 THEN users.id ELSE "" END) as user_id')
        ]);
        $value=User::joinSub($query1,'query1',function ($join){
            $join->on('users.id', '=', 'query1.id_to_join');
        })->whereIn('user_id', [1,2,3])->get();

in case your laravel version did not support joinsub, you can do it using query builder:

 $value=DB::table('users')->join(
            DB::raw('(select users.id as id_to_join ,(CASE WHEN users.id < 4 THEN users.id ELSE "" END) as user_id from users)subJoin')
            ,function($join){
            $join->on('users.id', '=', 'subJoin.id_to_join');
        })->whereIn('user_id', [1,2,3])->get();

Your logic seems to be that user ID values greater than 3 are to be disregarded. If so, then just check the id column directly in your call to whereIn() :

$users = \App\User::select([
    DB::raw('(CASE WHEN users.id < 4 THEN users.id ELSE "" END) as user_id')
]);
$users->whereIn('id', [1,2,3]);
return $users->get();

If you really needed to reuse the alias in the same level of the query, avoiding a subquery, you could use MySQL's overloaded HAVING clause:

$users = \App\User::select([
    DB::raw('(CASE WHEN users.id < 4 THEN users.id ELSE "" END) as user_id')
]);
$users->havingRaw('user_id in (1,2,3)')
return $users->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM