Laravel is convenient for debugging and printing sql log view

In actual development, we need to check whether the assembled SQL is what we need. In order to view the result, we directly print the SQL.

Use the getQueryLog method that comes with DB to print directly:

 

use Illuminate\Support\Facades\DB;
DB::connection()->enableQueryLog(); // 开启QueryLog 2 \App\User::find(1); 3 dump(DB::getQueryLog());

exit;

Get the following results, not intuitively view:

  array:1 [
    0 => array:3 [
      "query" => "select * from `fook_platform_ordercode` where `fook_platform_ordercode`.`id` = ? limit 1"
      "bindings" => array:1 [
        0 => 1
      ]
      "time" => 11.47
    ]
  ]

We now use another method to print out the complete SQL statement, and copy the following code to the boot method in AppServiceProvider:

code show as below:
\DB::listen(
    function ($sql) {
        foreach ($sql->bindings as $i => $binding) {
            if ($binding instanceof \DateTime) {
                $sql->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
            } else {
                if (is_string($binding)) {
                    $sql->bindings[$i] = "'$binding'";
                }
            }
        }

        // Insert bindings into query
        $query = str_replace(array('%', '?'), array('%%', '%s'), $sql->sql);

        $query = vsprintf($query, $sql->bindings);

        // Save the query to file
        $logFile = fopen(
            storage_path('logs' . DIRECTORY_SEPARATOR . date('Y-m-d') . '_query.log'),
            'a+'
        );
        fwrite($logFile, date('Y-m-d H:i:s') . ': ' . $query . PHP_EOL);
        fclose($logFile);
    }
);

Then the printed log is in

Guess you like

Origin blog.csdn.net/lchmyhua88/article/details/107298222