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

时间:2017-12-16 10:47:33

标签: php laravel laravel-5.2 laravel-5.5

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

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

输出是:

(
    [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
        )
)

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

select * from "order_items" where "order_items"."name" = 'test' and "order_items"."deleted_at" is null

我知道我可以用原始PHP做到这一点但是在laravel核心中是否有任何解决方案?

4 个答案:

答案 0 :(得分:3)

实际上我在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());
    }
}

只需将这三个功能放在helpers.php文件中,您就可以使用以下内容:

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

或者您可以使用

qld(); // for dump only

答案 1 :(得分:1)

是的,你是对的:/ 这是一个高度要求的功能,我不知道为什么它不是框架的一部分......

这不是最优雅的解决方案,但您可以这样做:



    function getPureSql($sql, $binds) {
        $result = "";

        $sql_chunks = explode('?', $sql);
        foreach ($sql_chunks as $key => $sql_chunk) {
            if (isset($binds[$key])) {
                $result .= $sql_chunk . '"' . $binds[$key] . '"';
            }
        }

        return $result;
    }

    $query = OrderItem::where('name', '=', 'test');
    $pure_sql_query = getPureSql($query->toSql(), $query->getBindings()); 

    // Or like this:
    $data = OrderItem::where('name', '=', 'test')->get();

    $log = DB::getQueryLog();
    $log = end($log);
    $pure_sql_query = getPureSql($log['query'], $log['bindings']);

答案 2 :(得分:0)

在这里,我扩展了@blaz的答案

在app \ Providers \ AppServiceProvider.php

在boot()方法上添加此

    if (env('APP_DEBUG')) {
        DB::listen(function($query) {
            File::append(
                storage_path('/logs/query.log'),
                self::queryLog($query->sql, $query->bindings) . "\n\n"
            );
        });
    }

并还添加了一个私有方法

private function queryLog($sql, $binds)
{
    $result = "";
    $sql_chunks = explode('?', $sql);

    foreach ($sql_chunks as $key => $sql_chunk) {
        if (isset($binds[$key])) {
            $result .= $sql_chunk . '"' . $binds[$key] . '"';
        }
    }

    $result .= $sql_chunks[count($sql_chunks) -1];

    return $result;
}

答案 3 :(得分:-2)

你可以这样做:


    OrderItem::where('name', '=', 'test')->toSql();