Generate The Raw MySQL Query From Laravel Query Builder

后端 未结 14 1354
醉话见心
醉话见心 2021-02-02 12:04

How can i get mysql query of a laravel query

Convert:

App\\User::where(\'balance\',\'>\',0)->where(...)-         


        
14条回答
  •  感情败类
    2021-02-02 12:42

    In Laravel 5.4 (I didn't check this in other versions), add this function into the "App"=>"Providers"=>"AppServiceProvider.php" .

    public function boot()
    {
    
        if (App::isLocal()) {
    
            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+'
                    );*/
                    Log::notice("[USER] $query");
                }
            );
        }
    }
    

    After that install, https://github.com/ARCANEDEV/LogViewer and then you can see every executed SQL queries without editing the code.

提交回复
热议问题