给定以下代码:
DB::table('users')->get();
我想得到上面的数据库查询生成器将生成的原始SQL查询字符串。在本例中,它将是SELECT*FROM用户。
我该怎么做?
给定以下代码:
DB::table('users')->get();
我想得到上面的数据库查询生成器将生成的原始SQL查询字符串。在本例中,它将是SELECT*FROM用户。
我该怎么做?
当前回答
您可以使用此包获取加载页面时正在执行的所有查询
https://github.com/barryvdh/laravel-debugbar
其他回答
虽然我很喜欢这个框架,但我讨厌它像垃圾一样运行。
DB::enableQueryLog()完全无用。DB::听同样没用。当我说$query->count()时,它显示了部分查询,但如果我执行$query->get(),它就没有什么好说的了。
唯一一个似乎能持续工作的解决方案是,故意在ORM参数中添加一些语法或其他错误,例如不存在的列/表名,在调试模式下在命令行上运行代码,最后将通过完整的“frickin”查询吐出SQL错误。否则,如果从web服务器运行,则希望错误出现在日志文件中。
对QueryBuilder实例使用toSql()方法。
DB::table('users')->toSql()将返回:
从用户中选择*`
这比连接事件侦听器更容易,而且还允许您在构建查询时随时检查查询的实际外观。
注意:此方法适用于查询生成器或Elquent,但使用toSql()代替first()或get()。不能使用此方法同时运行查询和获取SQL。
有很多信息已经得到了回答,我将发布我自己的发现,每当我需要在执行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;
希望这也有帮助。
试试看:
$results = DB::table('users')->toSql();
dd($results);
注意:get()已替换为toSql()以显示原始SQL查询。
如果您使用的不是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);