Laravel - 如何使用绑定参数获取查询?

fic*_*489 6 php laravel laravel-5.2 laravel-5.5

我可以用这种方式获取not-bind查询:

\DB::enableQueryLog();
$items = OrderItem::where('name', '=', 'test')->get();
$log = \DB::getQueryLog();
print_r($log);
Run Code Online (Sandbox Code Playgroud)

输出是:

(
    [0] => Array
        (
            [query] => select * from "order_items" where "order_items"."name" = ? and "order_items"."deleted_at" is null
            [bindings] => Array
                (
                    [0] => test
                )
            [time] => 0.07
        )
)
Run Code Online (Sandbox Code Playgroud)

但我真正需要的是绑定查询,如下所示:

select * from "order_items" where "order_items"."name" = 'test' and "order_items"."deleted_at" is null
Run Code Online (Sandbox Code Playgroud)

我知道我可以用原始PHP做到这一点但是laravel核心有什么解决方案吗?

Nar*_*dia 5

helpers.php实际上我已经为此创建了一个函数。helpers.php您还可以在文件中使用相同的函数

if (! function_exists('ql'))
{
    /**
     * Get Query Log
     *
     * @return array of queries
     */
    function ql()
    {
        $log = \DB::getQueryLog();

        $pdo = \DB::connection()->getPdo();

        foreach ($log as &$l)
        {
            $bindings = $l['bindings'];

            if (!empty($bindings))
            {
                foreach ($bindings as $key => $binding)
                {
                    // This regex matches placeholders only, not the question marks,
                    // nested in quotes, while we iterate through the bindings
                    // and substitute placeholders by suitable values.
                    $regex = is_numeric($key)
                        ? "/\?(?=(?:[^'\\\']*'[^'\\\']*')*[^'\\\']*$)/"
                        : "/:{$key}(?=(?:[^'\\\']*'[^'\\\']*')*[^'\\\']*$)/";

                    $l['query'] = preg_replace($regex, $pdo->quote($binding), $l['query'], 1);
                }
            }
        }

        return $log;
    }
}

if (! function_exists('qldd'))
{
    /**
     * Get Query Log then Dump and Die
     *
     * @return array of queries
     */
    function qldd()
    {
        dd(ql());
    }
}

if (! function_exists('qld'))
{
    /**
     * Get Query Log then Dump
     *
     * @return array of queries
     */
    function qld()
    {
        dump(ql());
    }
}
Run Code Online (Sandbox Code Playgroud)

只需将这三个函数放入您的helpers.php文件中,您就可以使用它们,如下所示:

$items = OrderItem::where('name', '=', 'test')->get();
qldd(); //for dump and die
Run Code Online (Sandbox Code Playgroud)

或者你可以使用

qld(); // for dump only
Run Code Online (Sandbox Code Playgroud)


小智 -2

您可以通过以下方式做到这一点:

    OrderItem::where('名称', '=', '测试')->toSql();