给定以下代码:
DB::table('users')->get();
我想得到上面的数据库查询生成器将生成的原始SQL查询字符串。在本例中,它将是SELECT*FROM用户。
我该怎么做?
给定以下代码:
DB::table('users')->get();
我想得到上面的数据库查询生成器将生成的原始SQL查询字符串。在本例中,它将是SELECT*FROM用户。
我该怎么做?
当前回答
Use:
$data = DB::select('select * from users where id = :id', ['id' => 1]);
print_r($data);
输出如下:
Array ( [0] => stdClass Object ( [id] => 1 [name] => parisa [last] => naderi [username] => png [password] => 2132 [role] => 0 ) )
其他回答
如果您使用的不是Laravel,而是Elquent包,那么:
use \Illuminate\Database\Capsule\Manager as Capsule;
use \Illuminate\Events\Dispatcher;
use \Illuminate\Container\Container;
$capsule = new Capsule;
$capsule->addConnection([
// connection details
]);
// Set the event dispatcher used by Eloquent models... (optional)
$capsule->setEventDispatcher(new Dispatcher(new Container));
// Make this Capsule instance available globally via static methods... (optional)
$capsule->setAsGlobal();
// Setup the Eloquent ORM...(optional unless you've used setEventDispatcher())
$capsule->bootEloquent();
// Listen for Query Events for Debug
$events = new Dispatcher;
$events->listen('illuminate.query', function($query, $bindings, $time, $name)
{
// Format binding data for sql insertion
foreach ($bindings as $i => $binding) {
if ($binding instanceof \DateTime) {
$bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
} else if (is_string($binding)) {
$bindings[$i] = "'$binding'";`enter code here`
}
}
// Insert bindings into query
$query = str_replace(array('%', '?'), array('%%', '%s'), $query);
$query = vsprintf($query, $bindings);
// Debug SQL queries
echo 'SQL: [' . $query . ']';
});
$capsule->setEventDispatcher($events);
有一种获取查询字符串的方法。
到SQL()
在我们的情况下,
DB::table('users')->toSql();
回来
select * from users
是返回SQL查询字符串的确切解决方案。。希望这有帮助。。。
您可以使用toSql方法-最简单的方法
DB::table('users')->toSql();
此外,如果您的查询中有绑定,并且希望查看带有绑定的查询。你不能用这样的东西:
$query = DB::table('table')->whereIn('some_field', [1,2,30]);
$sql_with_bindings = str_replace_array('?', $query->getBindings(), $query->toSql());
dd($sql_with_bindings);
在我看来,这将是初学者的最佳方法:
echo "<pre>";
print_r($query->toSql());
print_r($query->getBindings());
这里也描述了这一点。https://stackoverflow.com/a/59207557/9573341
第一个选项
当然,有一些方法可以只输出一个查询,并在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成为了一个很好的助手