DB::raw laravel 5.4 中的数组绑定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45710633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WHERE IN array binding in DB::raw laravel 5.4
提问by MrChrissss
I'm trying to bind an array in a raw WHERE IN
query in the Laravel DB
我正在尝试WHERE IN
在 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?
有人知道我能不能以某种方式做到这一点?
回答by gaurav
try it in laravel:
在 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.
为了防止 sql 注入,您可以使用我在下面提到的类似方法。
$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.
这对你有用。
回答by adriano machado
Try:
尝试:
$array = [2,5,9,7,5];
$arrPos = [];
$arrBind = [];
foreach ($array as $pos => $id) {
$arrPos[] = ":id_{$pos}";
$arrBind["id_{$pos}"] = $id;
}
$sql =
" SELECT * FROM test1 WHERE id IN (".implode(', ', $arrPos).") ";
$rs = DB::select($sql, $arrBind);
回答by linktoahref
or
或者
DB::table("test1")->whereIn('id', $arr)->get();
回答by Nasr
or Eloquent :
或雄辩:
$q= TestModel::where('id',$arr)->get();