给定以下代码:
DB::table('users')->get();
我想得到上面的数据库查询生成器将生成的原始SQL查询字符串。在本例中,它将是SELECT*FROM用户。
我该怎么做?
给定以下代码:
DB::table('users')->get();
我想得到上面的数据库查询生成器将生成的原始SQL查询字符串。在本例中,它将是SELECT*FROM用户。
我该怎么做?
当前回答
将此函数添加到应用程序中,只需调用。
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'”
其他回答
试试看:
$results = DB::table('users')->toSql();
dd($results);
注意:get()已替换为toSql()以显示原始SQL查询。
以下是我使用的解决方案:
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]);
});
请阅读代码中的注释。我知道,它并不完美,但对于我的日常调试来说,它还可以。它试图以或多或少的可靠性构建绑定查询。但是,不要完全信任它,数据库引擎以不同的方式对值进行转义,而这个短函数并没有实现这些值。所以,仔细观察结果。
我通过监听查询日志并附加到日志数组来实现:
//create query
$query=DB::table(...)...->where(...)...->orderBy(...)...
$log=[];//array of log lines
...
//invoked on query execution if query log is enabled
DB::listen(function ($query)use(&$log){
$log[]=$query;//enqueue query data to logs
});
//enable query log
DB::enableQueryLog();
$res=$query->get();//execute
要查看Laravel执行的查询,请使用Laravel查询日志
DB::enableQueryLog();
$queries = DB::getQueryLog();
第一种方式:
只需使用toSql()方法,
$query = DB::table('users')->get();
echo $query->toSql();
如果它不起作用,你可以从laravel文档中设置它。
第二种方式:
另一种方法是
数据库::getQueryLog()
但是如果它返回一个空数组,那么默认情况下它被禁用,
只需使用DB::enableQueryLog()启用即可:)
有关更多信息,请访问Github Issue了解更多信息。
希望有帮助:)