How to escape a query using an Eloquent model sele

2019-08-06 09:30发布

DB::select takes a second parameter as described here, but Eloquent::select does not.

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?

2条回答
\"骚年 ilove
2楼-- · 2019-08-06 09:52

You may use PDO or easier manually add binding to the Query:

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.

查看更多
Juvenile、少年°
3楼-- · 2019-08-06 10:02

Use 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`"
    )
)
查看更多
登录 后发表回答