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

前端 未结 4 1109
有刺的猬
有刺的猬 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:27

    For debugging this might come quite handy as it returns the SQL with the bindings, so you can instantly put it into the database console.

    /**
     * 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) {
            return is_numeric($binding) ? $binding : "'{$binding}'";
        })->toArray());
    }
    

提交回复
热议问题