Friday 21 February 2020

Laravel Raw query unable to use same parameter name twice I.E :=var1, :=var1,

// Raw query to get results
$results = DB::select('select * from users where id = :id', ['id' => 1]);
// note this will get an array with STD::class object, need to convert 
 * array(3) {
     *       [0]=>
     *      object(stdClass)#367 (7) {
     *           ["amount"]=>
     *            string(5) "70.00"
     *        }

        // Format data
        foreach ($raw_data as $raw_item) {
            // $raw_item is STDClass object
            $raw_item = json_decode(json_encode($raw_item), TRUE);

Instead of using ? to represent your parameter bindings, you may execute a query using named bindings:
$results = DB::select('select * from users where id = :id', ['id' => 1]);
In your case you ought to be able to run this:
DB::table('users as u')
    ->select('id')
    ->whereRaw('u.id > :id or u.id < :id or u.id = :id', [
        'id' => 2,
    ])
    ->first();
But it seems Laravel throws a QueryException with the message Invalid parameter number. I've reported this as a bug.
If you really want to use whereRaw you could instead build your array of parameters from a variable:
$id = 2;
DB::table('users as u')
    ->select('id')
    ->whereRaw('u.id > ? or u.id < ? or u.id = ?', [
        $id, $id, $id,
    ])
    ->first();
Or use array_fill to repeat the value for you:
$id = 2;
DB::table('users as u')
    ->select('id')
    ->whereRaw('u.id > ? or u.id < ? or u.id = ?', array_fill(0, 3, $id))
    ->first();
If you don't need whereRaw you can instead use other features of the query builder and build the query bit by bit, with the parameter coming from a variable:
$id = 2;
DB::table('users')
    ->select('id')
    ->where('id', '>', $id)
    ->orWhere('id', '<', $id)
    ->orWhere('id', $id')
    ->first();
https://stackoverflow.com/questions/35960535/laravel-query-builder-parameter-binding

No comments:

Post a Comment