WHERE IN array binding in DB::raw laravel 5.4

2019-08-17 14:10发布

问题:

I'm trying to bind an array in a raw WHERE IN query in the Laravel DB

example:

$arr = [1,2,3];
DB::select(DB::raw("select * from test1 WHERE id IN ? "), [$arr]);

for some reason the array is not being changed to the following query:

select * from test1 WHERE id IN (1,2,3)

does someone know if I can do this somehow?

回答1:

try it in laravel:

$arr = [1,2,3];
$result = DB::table('test1')->whereIn('id', $arr)->get();
dd($result);

And use this one for your raw query:

$arr = [1,2,3];
$arr = join(",",$arr);
$result =  DB::select(DB::raw("SELECT * FROM test1 WHERE id IN (".$arr.")"));
dd($result);

For preventing sql injection you use something like which i have mentioned below.

 $arr = [1,2];
 $arr = join(",",$arr);
 $result =  DB::select(DB::raw("SELECT * FROM test1 WHERE id IN (?,?)"),$arr);
 dd($result);

it will be work for you.



回答2:

or

DB::table("test1")->whereIn('id', $arr)->get();

https://laravel.com/docs/5.4/queries#where-clauses



回答3:

or Eloquent :

$q= TestModel::where('id',$arr)->get();