How can I get the raw query string from Laravel's query builder BEFORE executing the query?

前端 未结 4 1108
有刺的猬
有刺的猬 2020-12-15 16:16

I have a complex query created by a few conditions, and I would like to get the final SQL query from the builder object is about to execute. Can I do that?

4条回答
  •  佛祖请我去吃肉
    2020-12-15 16:42

    Piggy back off andi79h's answer. The function works well, except it's assuming binding would not have any quotes that could break the query.

    I added "addslashes" to $bindings to make it a bit safer. Although, ideally, it should be run through mysqli_real_escape_string() if you have an active connection to work with. https://www.php.net/manual/en/mysqli.real-escape-string.php

    /**
     * Combines SQL and its bindings
     *
     * @param \Eloquent $query
     * @return string
     */
    public static function getEloquentSqlWithBindings($query)
    {
        return vsprintf(str_replace('?', '%s', $query->toSql()), collect($query->getBindings())->map(function ($binding) {
            $binding = addslashes($binding);
            return is_numeric($binding) ? $binding : "'{$binding}'";
        })->toArray());
    }
    

提交回复
热议问题