简体   繁体   中英

How to escape a query using an Eloquent model select?

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?

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`"
    )
)

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.

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