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

问题描述 投票:6回答:4

我可以用这种方式获取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核心有什么解决方案吗?

php laravel laravel-5.2 laravel-5.5
4个回答
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
投票

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

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



    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']);


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

-2
投票

你可以这样做:


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

© www.soinside.com 2019 - 2024. All rights reserved.