给定以下代码:
DB::table('users')->get();
我想得到上面的数据库查询生成器将生成的原始SQL查询字符串。在本例中,它将是SELECT*FROM用户。
我该怎么做?
给定以下代码:
DB::table('users')->get();
我想得到上面的数据库查询生成器将生成的原始SQL查询字符串。在本例中,它将是SELECT*FROM用户。
我该怎么做?
当前回答
以下是我使用的解决方案:
DB::listen(function ($sql, $bindings, $time) {
$bound = preg_replace_callback("/\?/", function($matches) use ($bindings) {
static $localBindings;
if (!isset($localBindings)) {
$localBindings = $bindings;
}
$val = array_shift($localBindings);
switch (gettype($val)) {
case "boolean":
$val = ($val === TRUE) ? 1 : 0; // mysql doesn't support BOOL data types, ints are widely used
// $val = ($val === TRUE) ? "'t'" : "'f'"; // todo: use this line instead of the above for postgres and others
break;
case "NULL":
$val = "NULL";
break;
case "string":
case "object":
$val = "'". addslashes($val). "'"; // correct escaping would depend on the RDBMS
break;
}
return $val;
}, $sql);
array_map(function($x) {
(new \Illuminate\Support\Debug\Dumper)->dump($x);
}, [$sql, $bindings, $bound]);
});
请阅读代码中的注释。我知道,它并不完美,但对于我的日常调试来说,它还可以。它试图以或多或少的可靠性构建绑定查询。但是,不要完全信任它,数据库引擎以不同的方式对值进行转义,而这个短函数并没有实现这些值。所以,仔细观察结果。
其他回答
用于获取带有绑定的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());
虽然我很喜欢这个框架,但我讨厌它像垃圾一样运行。
DB::enableQueryLog()完全无用。DB::听同样没用。当我说$query->count()时,它显示了部分查询,但如果我执行$query->get(),它就没有什么好说的了。
唯一一个似乎能持续工作的解决方案是,故意在ORM参数中添加一些语法或其他错误,例如不存在的列/表名,在调试模式下在命令行上运行代码,最后将通过完整的“frickin”查询吐出SQL错误。否则,如果从web服务器运行,则希望错误出现在日志文件中。
有很多信息已经得到了回答,我将发布我自己的发现,每当我需要在执行sql查询之前输出它时,我都会使用这些发现。
考虑以下示例:
$user = DB::table('user')->where('id',1);
echo $user->toSql();
echo$user->toSql()=这将只输出原始查询,但不会显示传递的参数。
要输出带有传递参数的查询,我们可以使用laravel getBindings()和helper str_replace_array,如下所示:
$queryWithParam = str_replace_array('?',$user->getBindings(),$user->toSql());
echo $queryWithParam;
希望这也有帮助。
我创建了一些简单的函数来从一些查询中获取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 ],
// ]
第一个选项
当然,有一些方法可以只输出一个查询,并在phpMyAdmin或其他工具中对其进行调试,以了解查询的执行方式。
一种将查询与变量(也称为绑定)一起转储的好方法,您可以将以下函数添加为项目中的公共助手
function queryToSQL($query, $logQuery = true)
{
$addSlashes = str_replace('?', "'?'", $query->toSql());
$sql = str_replace('%', '#', $addSlashes);
$sql = str_replace('?', '%s', $sql);
$sql = vsprintf($sql, $query->getBindings());
$sql = str_replace('#', '%', $sql);
if ($logQuery) {
Log::debug($sql);
}
return $sql;
}
第二个选项
这是另一种方法,而不是转储每个查询,您可以使用Telescope,该工具可以让您更深入地了解可能在后台启动的所有查询,以及每个查询花费的时间以及显示的所有绑定
第三种选择
Laravel Debugbar是一个非常棒的插件,它可以帮助您在小的底部栏下调试所有内容,但这仅适用于基于UI的活动,对于API或命令,调试方式被忽略了,Telescope成为了一个很好的助手