Laravel how to get query with bindings?

前端 未结 14 848
小蘑菇
小蘑菇 2021-01-31 15:58

I have some query that I need to pass to another query using query builder

$query = DB::table(\'table\')->whereIn(\'some_field\', [1,2,30])->toSql();

Mode         


        
14条回答
  •  萌比男神i
    2021-01-31 16:43

    Since the other answers do not properly quote the expressions, here is my approach. It uses the escaping function, that belongs to the current database connection.

    It replaces the question marks one by one with the corresponding binding, which is retrieved from $bindings via array_shift(), consuming the array in the process. Note, that $bindings has to be passed by reference for this to work.

    function getSql($query)
    {
            $bindings = $query->getBindings();
    
            return preg_replace_callback('/\?/', function ($match) use (&$bindings, $query) {
                return $query->getConnection()->getPdo()->quote(array_shift($bindings));
            }, $query->toSql());
    }
    

提交回复
热议问题