[英]How to escape a query using an Eloquent model select?
DB::select
takes a second parameter as described here , but Eloquent::select
does not. DB::select
具有第二个参数,如此处所述 ,而Eloquent::select
没有。
Here's my query: 这是我的查询:
Feature::where('company_id', Auth::user()->company_id)
->select('id','name',DB::raw("exists(select * from vehicle_features vf where vf.vehicle_id=$id and vf.feature_id=feature.id) as `checked`"))
->orderBy('name')->get(),
How can I ensure $id
is escaped properly? 如何确保
$id
正确转义?
Use DB::getPdo()->quote($id)
. 使用
DB::getPdo()->quote($id)
。
->select(
'id',
'name',
DB::raw(
"exists(select * from vehicle_features vf where vf.vehicle_id="
. DB::getPdo()->quote($id)
. " and vf.feature_id=feature.id) as `checked`"
)
)
You may use PDO or easier manually add binding to the Query: 您可以使用PDO或更容易地手动将绑定添加到查询:
Feature::select(
'id',
'name',
// replace $id here
DB::raw("exists(select * from vehicle_features vf where vf.vehicle_id=? and vf.feature_id=feature.id) as `checked`"))
// and add this part
->addBinding($id)
->where('company_id', Auth::user()->company_id)
->orderBy('name')->get();
edit: as stated in the comments below, bindings are bugged and methods order does matter, so the above will work as expected. 编辑:如下面的注释中所述,绑定是bug和方法顺序确实很重要,因此上述内容将按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.