mardi 16 juillet 2019

Laravel DB::statement is not able to prepare values properly for the queries that involves column expressions

I wanna know the problem that is arising between DB::statement and DB::unprepared queries, So apparently DB::statement methods are not functioning with queries that do expressions on columns itself, something like this:

UPDATE tags SET ? = ? + 2 WHERE ? > ? AND user_id = ? AND tree_id = ?

This results into SQL as:

UPDATE tags SET rgt = rgt + 2 WHERE rgt > 2 AND user_id = 1 AND tree_id = 1

^This query when used within mysql interpreter works absolutely fine but shits brick with laravel's DB::statement method (it works fine with unprepared method btw).

Whats the reason behind this mismatch?

The error it pops up with is SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax which is weird because its correct syntax and already works fine with mysql.

So the statement method is doing this:

    {
        return $this->run($query, $bindings, function ($query, $bindings) {
            if ($this->pretending()) {
                return true;
            }
            $statement = $this->getPdo()->prepare($query);
            $this->bindValues($statement, $this->prepareBindings($bindings));
            $this->recordsHaveBeenModified();
            return $statement->execute();
        });
    }

While the unprepared one:

    {
        return $this->run($query, [], function ($query) {
            if ($this->pretending()) {
                return true;
            }
            $this->recordsHaveBeenModified(
                $change = ($this->getPdo()->exec($query) === false ? false : true)
            );
            return $change;
        });
    }

I think the issue is arriving at either the prepare method.

Bonus Question: Moreover, if you know any Eloquent way of handling this query, it'd be awesome! (In the sense how to handle column level expressions via native, where, update, etc methods.)



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire