从Laravel查询生成器生成原始MySQL查询

时间:2017-06-12 10:23:39

标签: php mysql laravel

如何mysql查询laravel查询

转换:

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

SELECT * FROM users WHERE `balance`>0 and ...

13 个答案:

答案 0 :(得分:28)

使用laravel的toSql()方法来执行查询,如

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

但是Laravel不会在查询中显示参数,因为它们在准备查询后被绑定。要获取绑定参数,请使用此

$query=App\User::where('balance','>',0)->where(...);
print_r($query->getBindings() );

将查询日志设为DB::enableQueryLog(),然后输出到上次查询运行的屏幕,您可以使用此功能,

dd(DB::getQueryLog());

答案 1 :(得分:4)

您可以将此功能添加到助手

function getRealQuery($query, $dumpIt = false)
{
    $params = array_map(function ($item) {
        return "'{$item}'";
    }, $query->getBindings());
    $result = str_replace_array('\?', $params, $query->toSql());
    if ($dumpIt) {
        dd($result);
    }
    return $result;
}

并使用如下:

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

答案 2 :(得分:2)

要打印原始sql查询,请尝试:

DB::enableQueryLog();
// Your query here
$queries = DB::getQueryLog();
print_r($queries);

Reference

答案 3 :(得分:2)

当我想看到生成的SQL时,我会执行以下操作,而不是使用print语句或“dd s”干扰应用程序:

DB::listen(function ($query) { 
    Log::info($query->sql, $query->bindings);
});

// (DB and Log are the facades in Illuminate\Support\Facades namespace)

这会将sql输出到Laravel日志(位于storage/logs/laravel.log)。用于跟踪写入此文件的有用命令是

tail -n0 -f storage/logs/laravel.log

答案 4 :(得分:2)

在没有任何代码更改的情况下显示Laravel中使用的所有查询的简单方法是安装LaravelDebugBar(https://laravel-news.com/laravel-debugbar)。

作为功能的一部分,您会收到一个标签,其中会显示网页所使用的所有查询。

答案 5 :(得分:1)

要在laravel中获取mysql查询,您需要将查询记录为

DB::enableQueryLog();
App\User::where('balance','>',0)->where(...)->get();
print_r(DB::getQueryLog());

检查参考:https://laravel.com/docs/5.0/database#query-logging

答案 6 :(得分:1)

这是一个帮助函数,它告诉你最后执行的SQL。

use DB;
public static function getLastSQL()
{
    $queries = DB::getQueryLog();
    $last_query = end($queries);
          // last_query is the SQL with with data binding like 
          //   { 
          //       select ? from sometable where field = ? and field2 = ? ;
          //       param1,
          //       param2,
          //       param3,
          //   }
          //   which is hard to read.
    $last_query = bindDataToQuery($last_query);     
          // here, last_query is the last SQL you have executed as normal SQL
          //     select param1 from sometable where field=param2 and field2 = param3;
    return $last_query
}

这是bindDataToQuery函数,谁填写'?'空白与空白。

protected static function bindDataToQuery($queryItem){
    $query = $queryItem['query'];
    $bindings = $queryItem['bindings'];
    $arr = explode('?',$query);
    $res = '';
    foreach($arr as $idx => $ele){
        if($idx < count($arr) - 1){
            $res = $res.$ele."'".$bindings[$idx]."'";
        }
    }
    $res = $res.$arr[count($arr) -1];
    return $res;
}

答案 7 :(得分:1)

在Laravel 5.4中(我在其他版本中没有检查过),将此功能添加到 &#34;应用&#34; = GT;&#34;商&#34; = GT;&#34; AppServiceProvider.php&#34;

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");
            }
        );
    }
}

安装完成后, https://github.com/ARCANEDEV/LogViewer 然后您可以在不编辑代码的情况下查看每个执行的SQL查询。

答案 8 :(得分:1)

方法1

要打印单个查询,请使用laravel的toSql()方法来执行查询,如

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

方法2

Laravel可以选择在内存中登录为当前请求运行的所有查询。但在某些情况下,例如插入大量行时,这可能会导致应用程序使用过多的内存,因此您应该避免这种情况。

要启用日志,您可以使用 enableQueryLog 方法

DB::connection()->enableQueryLog();

要获取已执行查询的数组,可以使用 getQueryLog 方法

$queries = DB::getQueryLog();

您可以在此处获取更多详细信息Laravel Enable Query Log

方法3

在不启用查询日志的情况下显示Laravel中使用的所有查询的另一种方法是从此处安装 LaravelDebugBar Laravel Debug Bar。 它是一个软件包,允许您在开发过程中快速轻松地查看应用程序。

答案 9 :(得分:1)

尝试一下:

$results = App\User::where('balance','>',0)->where(...)->toSql();
dd($results);

注意:get()已替换为toSql()以显示原始SQL查询。

答案 10 :(得分:-1)

下面是一个非常简单快捷的方法 写入列的名称错误,如“平衡”,写入'balancedd',当您执行包含所有参数的代码并且找不到该列时,查询将显示在错误屏幕上。

答案 11 :(得分:-1)

DB::enableQueryLog(); (Query) $d= DB::getQueryLog(); print"<pre>"; print_r ($d); print"</pre>";

您将获得刚刚运行的mysql查询。

答案 12 :(得分:-4)

在Laravel甚至PHP中实际上没有这样的东西,因为PHP在内部将带有查询字符串的参数发送到数据库,在那里它(可能)被解析为原始查询字符串。

接受的答案实际上是乐观的解决方案,有点&#34;可选择工作&#34;。