次のコードがあるとします。
DB::table('users')->get();
上記のデータベース クエリ ビルダーが生成する生の SQL クエリ文字列を取得したいと考えています。この例では、 になりますSELECT * FROM users
。
どうすればいいですか?
次のコードがあるとします。
DB::table('users')->get();
上記のデータベース クエリ ビルダーが生成する生の SQL クエリ文字列を取得したいと考えています。この例では、 になりますSELECT * FROM users
。
どうすればいいですか?
toSql()
インスタンスでメソッドを使用しQueryBuilder
ます。
DB::table('users')->toSql()
戻ります:
select * from `users`
これは、イベント リスナーを接続するよりも簡単で、クエリを作成しているときに、クエリが実際にどのように表示されるかを確認することもできます。
注: このメソッドは、クエリ ビルダーまたは Eloquent で機能しますが、またはtoSql()
の代わりに使用されます。このメソッドを使用して、クエリを実行すると同時に SQL を取得することはできません。first()
get()
雄弁にはクエリ文字列を取得するメソッドがあります。
toSQL()
私たちの場合には、
DB::table('users')->toSql();
戻る
select * from users
SQLクエリ文字列を返す正確なソリューションです..これが役立つことを願っています...
DB::enableQueryLog();
$queries = DB::getQueryLog();
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);
laravel 5.5.Xの場合
アプリケーションによって実行された各 SQL クエリを受け取りたい場合は、listen メソッドを使用できます。このメソッドは、クエリのログ記録やデバッグに役立ちます。クエリ リスナーをサービス プロバイダーに登録できます。
<?php
namespace App\Providers;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
DB::listen(function ($query) {
// $query->sql
// $query->bindings
// $query->time
});
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
//
}
}
このパッケージを使用して、ページの読み込み時に実行されているすべてのクエリを取得できます
https://github.com/barryvdh/laravel-debugbar
Tinker を使用していて、形成された SQL クエリをログに記録したい場合は、次のことができます。
$ php artisan tinker
Psy Shell v0.9.9 (PHP 7.3.5 — cli) by Justin Hileman
>>> DB::listen(function ($query) { dump($query->sql); dump($query->bindings); dump($query->time); });
=> null
>>> App\User::find(1)
"select * from `users` where `users`.`id` = ? limit 1"
array:1 [
0 => 1
]
6.99
=> App\User {#3131
id: 1,
name: "admin",
email: "admin@example.com",
created_at: "2019-01-11 19:06:23",
updated_at: "2019-01-11 19:06:23",
}
>>>
時計仕掛けを使用できます
Clockwork は、PHP 開発用の Chrome 拡張機能です。新しいパネルで開発者ツールを拡張し、PHP アプリケーションのデバッグとプロファイリングに役立つあらゆる種類の情報を提供します。これには、リクエスト、ヘッダー、データの取得と投稿、Cookie、セッション データ、データベース クエリに関する情報が含まれます。ルート、アプリケーション ランタイムの視覚化など。
しかし、Firefoxでも動作します
Laravel を使用していないが、Eloquent パッケージを使用している場合:
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 とバインドを取得する単純な関数をいくつか作成しました。
/**
* 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 ],
// ]
クエリログをリッスンし、ログ配列に追加することでそれを行いました:
//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