如何在Laravel 5中执行查询?DB :: getQueryLog()返回空数组

Ars*_*sen 161 php logging laravel laravel-5

我正在尝试查看查询的日志,但DB::getQueryLog()只是返回一个空数组:

$user = User::find(5);
print_r(DB::getQueryLog());
Run Code Online (Sandbox Code Playgroud)

结果

Array
(
)
Run Code Online (Sandbox Code Playgroud)

如何查看此查询的日志?

Mar*_*yan 242

默认情况下,Laravel 5中禁用查询日志:https: //github.com/laravel/framework/commit/e0abfe5c49d225567cb4dfd56df9ef05cc297448

您需要通过调用以下命令启用查询日志:

DB::enableQueryLog();
Run Code Online (Sandbox Code Playgroud)

或注册事件监听器:

DB::listen(
    function ($sql, $bindings, $time) {
        //  $sql - select * from `ncv_users` where `ncv_users`.`id` = ? limit 1
        //  $bindings - [5]
        //  $time(in milliseconds) - 0.38 
    }
);  
Run Code Online (Sandbox Code Playgroud)

一些技巧

1.多个DB连接

如果您有多个数据库连接,则必须指定要记录的连接

要启用查询日志my_connection:

DB::connection('my_connection')->enableQueryLog();
Run Code Online (Sandbox Code Playgroud)

获取查询日志my_connection:

print_r(
   DB::connection('my_connection')->getQueryLog()
);
Run Code Online (Sandbox Code Playgroud)

2.在哪里启用查询日志?

对于HTTP请求生命周期,您可以在handle某些BeforeAnyDbQueryMiddleware 中间件的方法中启用查询日志,然后terminate在同一中间件的方法中检索执行的查询.

class BeforeAnyDbQueryMiddleware
{
    public function handle($request, Closure $next)
    {
        DB::enableQueryLog();
        return $next($request);
    }

    public function terminate($request, $response)
    {
        // Store or dump the log data...
        dd(
            DB::getQueryLog()
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

中间件的链不会为工匠命令运行,因此对于CLI执行,您可以在artisan.start事件侦听器中启用查询日志.

例如,您可以将其放在bootstrap/app.php文件中

$app['events']->listen('artisan.start', function(){
    \DB::enableQueryLog();
});
Run Code Online (Sandbox Code Playgroud)

记忆

Laravel将所有查询保存在内存中.因此,在某些情况下,例如插入大量行或具有大量查询的长时间运行作业时,这可能会导致应用程序使用过多的内存.

在大多数情况下,您只需要查询日志进行调试,如果是这种情况,我建议您仅为开发启用它.

if (App::environment('local')) {
    // The environment is local
    DB::enableQueryLog();
}
Run Code Online (Sandbox Code Playgroud)

参考

  • 如果您的系统使用多个数据库连接,则必须指定它,否则它可能返回空数组:`\ DB :: connection('myconnection') - > enableQueryLog(); 的print_r(\ DB ::连接( 'MyConnection的') - > getQueryLog());` (6认同)
  • 请注意,在 Laravel 5.4 中,`DB::listen` 回调函数具有不同的签名。更像是这样:`DB::listen(function($query) { $sql = $query->sql; $bindings = $query->bindings; $time = $query->time; ... }); ` (2认同)

Ske*_*ets 42

如果您真正关心的是实际查询(最后一次运行)以进行快速调试:

DB::enableQueryLog();

# your laravel query builder goes here

$laQuery = DB::getQueryLog();

$lcWhatYouWant = $laQuery[0]['query']; # <-------

# optionally disable the query log:
DB::disableQueryLog();
Run Code Online (Sandbox Code Playgroud)

做一个print_r()$laQuery[0]得到充分的查询,包括绑定.($lcWhatYouWant上面的变量将替换变量??)

如果你使用的不是主mysql连接,你需要使用这些:

print_r()

$laQuery[0]

(你的连接名称是"mysql2")


Rub*_*uíz 13

把它放在routes.php文件中:

\Event::listen('Illuminate\Database\Events\QueryExecuted', function ($query) {
    echo'<pre>';
    var_dump($query->sql);
    var_dump($query->bindings);
    var_dump($query->time);
    echo'</pre>';
});
Run Code Online (Sandbox Code Playgroud)

由msurguy提交,此页面中的源代码.您将在评论中找到laravel 5.2的此修订代码.


Luí*_*ruz 11

显然,在Laravel 5.2中,闭包DB::listen只接收一个参数.

因此,如果您想DB::listen在Laravel 5.2中使用,您应该执行以下操作:

DB::listen(
    function ($sql) {
        // $sql is an object with the properties:
        //  sql: The query
        //  bindings: the sql query variables
        //  time: The execution time for the query
        //  connectionName: The name of the connection

        // To save the executed queries to file:
        // Process the sql and the bindings:
        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);
    }
);
Run Code Online (Sandbox Code Playgroud)


小智 10

您需要先启用查询日志记录

__CODE__

如果在应用程序启动之前启用查询日志记录会更好,您可以在BeforeMiddleware中执行,然后在AfterMiddleware中检索已执行的查询.


don*_*ona 8

使用toSql()而不是get()这样:

$users = User::orderBy('name', 'asc')->toSql();
echo $users;
// Outputs the string:
'select * from `users` order by `name` asc'
Run Code Online (Sandbox Code Playgroud)


lar*_*arp 7

对于laravel 5.8,您只需添加dddump即可

例如:

DB::table('users')->where('votes', '>', 100)->dd();
Run Code Online (Sandbox Code Playgroud)

要么

DB::table('users')->where('votes', '>', 100)->dump();
Run Code Online (Sandbox Code Playgroud)

参考:https : //laravel.com/docs/5.8/queries#debugging