给定以下代码:

DB::table('users')->get();

我想得到上面的数据库查询生成器将生成的原始SQL查询字符串。在本例中,它将是SELECT*FROM用户。

我该怎么做?


当前回答

如果你使用laravel 5.1和MySQL,你可以使用我制作的这个函数:

/*
 *  returns SQL with values in it
 */
function getSql($model)
{
    $replace = function ($sql, $bindings)
    {
        $needle = '?';
        foreach ($bindings as $replace){
            $pos = strpos($sql, $needle);
            if ($pos !== false) {
                if (gettype($replace) === "string") {
                     $replace = ' "'.addslashes($replace).'" ';
                }
                $sql = substr_replace($sql, $replace, $pos, strlen($needle));
            }
        }
        return $sql;
    };
    $sql = $replace($model->toSql(), $model->getBindings());
    
    return $sql;
}

作为输入参数,可以使用以下任一项

照明\数据库\口才\生成器照亮\数据库\口才\关系\ HasMany照明\数据库\查询\生成器

其他回答

DB::QueryLog()仅在使用$builder->get()执行查询后才起作用。

如果要在执行查询之前或不执行查询时获取原始查询,可以使用$builder->toSql()方法。

获取原始SQL并替换“?”的示例具有实际绑定值:

$query = str_replace(array('?'), array('\'%s\''), $builder->toSql());
$query = vsprintf($query, $builder->getBindings());
dump($query);

$result = $builder->get();

或者,您可以故意触发错误,例如,使用不存在的表或列。然后,您可以在异常消息中看到生成的查询。

你可以使用发条

Clockwork是一个用于PHP开发的Chrome扩展,通过一个新面板扩展了Developer Tools,该面板提供了用于调试和分析PHP应用程序的各种信息,包括请求、标头、获取和发布数据、cookie、会话数据、数据库查询、路由、应用程序运行时可视化等信息。

但也适用于firefox

以下是我使用的解决方案:

DB::listen(function ($sql, $bindings, $time) {
    $bound = preg_replace_callback("/\?/", function($matches) use ($bindings) {
        static $localBindings;
        if (!isset($localBindings)) {
            $localBindings = $bindings;
        }
        $val = array_shift($localBindings);

        switch (gettype($val)) {
            case "boolean":
                $val = ($val === TRUE) ? 1 : 0;  // mysql doesn't support BOOL data types, ints are widely used
                // $val = ($val === TRUE) ? "'t'" : "'f'";   // todo: use this line instead of the above for postgres and others
                break;

            case "NULL":
                $val = "NULL";
                break;

            case "string":
            case "object":
                $val = "'". addslashes($val). "'";   // correct escaping would depend on the RDBMS
                break;
        }
        return $val;
    }, $sql);
    array_map(function($x) { 
        (new \Illuminate\Support\Debug\Dumper)->dump($x); 
    }, [$sql, $bindings, $bound]);
});

请阅读代码中的注释。我知道,它并不完美,但对于我的日常调试来说,它还可以。它试图以或多或少的可靠性构建绑定查询。但是,不要完全信任它,数据库引擎以不同的方式对值进行转义,而这个短函数并没有实现这些值。所以,仔细观察结果。

有一种获取查询字符串的方法。

到SQL()

在我们的情况下,

 DB::table('users')->toSql(); 

回来

select * from users

是返回SQL查询字符串的确切解决方案。。希望这有帮助。。。

在我看来,这将是初学者的最佳方法:

echo "<pre>";
print_r($query->toSql());
print_r($query->getBindings());

这里也描述了这一点。https://stackoverflow.com/a/59207557/9573341