给定以下代码:
DB::table('users')->get();
我想得到上面的数据库查询生成器将生成的原始SQL查询字符串。在本例中,它将是SELECT*FROM用户。
我该怎么做?
给定以下代码:
DB::table('users')->get();
我想得到上面的数据库查询生成器将生成的原始SQL查询字符串。在本例中,它将是SELECT*FROM用户。
我该怎么做?
当前回答
将此代码添加到AppServiceProvider并获取日志文件
\DB::listen(function ($query) {
\Log::info(
$query->sql,
$query->bindings,
$query->time
);
});
其他回答
以下是我使用的解决方案:
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]);
});
请阅读代码中的注释。我知道,它并不完美,但对于我的日常调试来说,它还可以。它试图以或多或少的可靠性构建绑定查询。但是,不要完全信任它,数据库引擎以不同的方式对值进行转义,而这个短函数并没有实现这些值。所以,仔细观察结果。
您可以收听“illumination.query”事件。在查询之前,添加以下事件侦听器:
Event::listen('illuminate.query', function($query, $params, $time, $conn)
{
dd(array($query, $params, $time, $conn));
});
DB::table('users')->get();
这将打印出如下内容:
array(4) {
[0]=>
string(21) "select * from "users""
[1]=>
array(0) {
}
[2]=>
string(4) "0.94"
[3]=>
string(6) "sqlite"
}
将此代码添加到AppServiceProvider并获取日志文件
\DB::listen(function ($query) {
\Log::info(
$query->sql,
$query->bindings,
$query->time
);
});
下面是一个完美的例子:
https://laravel.com/docs/5.8/database#listening-用于查询事件
打开app\Providers\AppServiceProvider.php并将以下内容添加到Boot()函数中:
DB::listen(function ($query) {
var_dump([
$query->sql,
$query->bindings,
$query->time
]);
});
因此,您不需要在每个函数中放置DB::enableQuerylog()和DB::getQuerylog(()。
要查看Laravel执行的查询,请使用Laravel查询日志
DB::enableQueryLog();
$queries = DB::getQueryLog();