毕竟 laravel 可以记录 sql 查询吗?

Can laravel log sql queries after all?

Illuminate/Database/Connection.php中我可以看到:

/**
 * Indicates whether queries are being logged.
 *
 * @var bool
 */
protected $loggingQueries = false;

/**
 * Enable the query log on the connection.
 *
 * @return void
 */                                                                                                                                              public function enableQueryLog()
{
    $this->loggingQueries = true;
}

/**
 * Disable the query log on the connection.
 *
 * @return void
 */
public function disableQueryLog()
{
    $this->loggingQueries = false;
}

/**
 * Determine whether we're logging queries.
 *
 * @return bool
 */
public function logging()
{
    return $this->loggingQueries;
}

/**
 * Run a SQL statement and log its execution context.
 *
 * @param  string    $query
 * @param  array     $bindings
 * @param  \Closure  $callback
 * @return mixed
 *
 * @throws \Illuminate\Database\QueryException
 */
protected function run($query, $bindings, Closure $callback)
{
    ...

    $this->logQuery($query, $bindings, $time);

    return $result;
}

/**
 * Log a query in the connection's query log.
 *
 * @param  string  $query
 * @param  array   $bindings
 * @param  float|null  $time
 * @return void                                                                                                                                   */
public function logQuery($query, $bindings, $time = null)                                                                                        {
    ...

    if ($this->loggingQueries) {                                                                                                                         $this->queryLog[] = compact('query', 'bindings', 'time');
    }
}

这些数据是否存储在某个地方?如果可以,如何在全球范围内启用它?

我会使用 middleware 来启用它。这将允许您启用选项(例如仅在 local 环境等中)。

您可以使用 dd() 或使用 Log::info() 等收集信息。例如:

namespace App\Http\Middleware;

use DB;
use Log;
use Closure;

class EnableQueryLogMiddleware
{
    public function handle($request, Closure $next)
    {
        if (env('local')) {
            DB::enableQueryLog();
        }

        return $next($request);
    }

    public function terminate($request, $response)
    {
        // Here you can either Log it, DD, etc.
        dd(DB::getQueryLog());
        Log::info(DB::getQueryLog());
    }
}