给定以下代码:

DB::table('users')->get();

我想得到上面的数据库查询生成器将生成的原始SQL查询字符串。在本例中,它将是SELECT*FROM用户。

我该怎么做?


当前回答

试试看:

$results = DB::table('users')->toSql();
dd($results);

注意:get()已替换为toSql()以显示原始SQL查询。

其他回答

这是我放在基础模型类中的函数。只需将查询生成器对象传递给它,就会返回SQL字符串。

function getSQL($builder) {
  $sql = $builder->toSql();
  foreach ( $builder->getBindings() as $binding ) {
    $value = is_numeric($binding) ? $binding : "'".$binding."'";
    $sql = preg_replace('/\?/', $value, $sql, 1);
  }
  return $sql;
}

打印上次查询

DB::enableQueryLog();

$query        = DB::getQueryLog();
$lastQuery    = end($query);
print_r($lastQuery);

用于获取带有绑定的SQL查询的“可宏”替换。

在AppServiceProvider boot()方法中添加以下宏函数。\Illuminate\Database\Query\Builder::宏('toRawSql',function(){return array_reduce($this->getBindings(),函数($sql,$binding){return preg_replace('/\?/',is_numeric($binding)$绑定:“”$结合“'”,$sql,1);},$this->to SQL());});为Elquent Builder添加别名。(Laravel 5.4+)\Illuminate\Database\Elquent\Builder::宏('toRawSql',函数(){return($this->getQuery()->toRawSql());});然后照常调试。(Laravel 5.4+)例如,查询生成器\日志::debug(\DB::table('users')->limit(1)->toRawSql())例如,Elquent Builder\日志::debug(\App\User::limit(1)->toRawSql());

注意:从Laravel 5.1到5.3,由于Elquent Builder不使用Macroable特性,因此不能在RawSql中添加Elquent生成器的别名。遵循以下示例以实现相同的效果。

例如,Elquent Builder(Laravel 5.1-5.3)

\Log::debug(\App\User::limit(1)->getQuery()->toRawSql());

我创建了一些简单的函数来从一些查询中获取SQL和绑定。

/**
 * getSql
 *
 * Usage:
 * getSql( DB::table("users") )
 * 
 * Get the current SQL and bindings
 * 
 * @param  mixed  $query  Relation / Eloquent Builder / Query Builder
 * @return array          Array with sql and bindings or else false
 */
function getSql($query)
{
    if( $query instanceof Illuminate\Database\Eloquent\Relations\Relation )
    {
        $query = $query->getBaseQuery();
    }

    if( $query instanceof Illuminate\Database\Eloquent\Builder )
    {
        $query = $query->getQuery();
    }

    if( $query instanceof Illuminate\Database\Query\Builder )
    {
        return [ 'query' => $query->toSql(), 'bindings' => $query->getBindings() ];
    }

    return false;
}

/**
 * logQuery
 *
 * Get the SQL from a query in a closure
 *
 * Usage:
 * logQueries(function() {
 *     return User::first()->applications;
 * });
 * 
 * @param  closure $callback              function to call some queries in
 * @return Illuminate\Support\Collection  Collection of queries
 */
function logQueries(closure $callback) 
{
    // check if query logging is enabled
    $logging = DB::logging();

    // Get number of queries
    $numberOfQueries = count(DB::getQueryLog());

    // if logging not enabled, temporarily enable it
    if( !$logging ) DB::enableQueryLog();

    $query = $callback();

    $lastQuery = getSql($query);

    // Get querylog
    $queries = new Illuminate\Support\Collection( DB::getQueryLog() );

    // calculate the number of queries done in callback
    $queryCount = $queries->count() - $numberOfQueries;

    // Get last queries
    $lastQueries = $queries->take(-$queryCount);

    // disable query logging
    if( !$logging ) DB::disableQueryLog();

    // if callback returns a builder object, return the sql and bindings of it
    if( $lastQuery )
    {
        $lastQueries->push($lastQuery);
    }

    return $lastQueries;
}

用法:

getSql( DB::table('users') );
// returns 
// [
//     "sql" => "select * from `users`",
//     "bindings" => [],
// ]

getSql( $project->rooms() );
// returns
// [
//     "sql" => "select * from `rooms` where `rooms`.`project_id` = ? and `rooms`.`project_id` is not null",
//     "bindings" => [ 7 ],
// ]

将此函数添加到应用程序中,只需调用。

function getQuery($sql){
        $query = str_replace(array('?'), array('\'%s\''), $sql->toSql());
        $query = vsprintf($query, $sql->getBindings());     
        return $query;
}

输出:“根据updated_at desc limit 25 offset 0从用户中选择*,其中lang='en',status='1'”