Laravel how to get query with bindings?

前端 未结 14 704
小蘑菇
小蘑菇 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条回答
  • 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());
    }
    
    0 讨论(0)
  • 2021-01-31 16:43

    I created this function. It is partial, might be parameters which are not covered, for me it was enough.
    More than welcomed to add your improvements in a comment!

    function getFullSql($query) {
      $sqlStr = $query->toSql();
      foreach ($query->getBindings() as $iter=>$binding) {
    
        $type = gettype($binding);
        switch ($type) {
          case "integer":
          case "double":
            $bindingStr = "$binding";
            break;
          case "string":
            $bindingStr = "'$binding'";
            break;
          case "object":
            $class = get_class($binding);
            switch ($class) {
              case "DateTime":
                $bindingStr = "'" . $binding->format('Y-m-d H:i:s') . "'";
                break;
              default:
                throw new \Exception("Unexpected binding argument class ($class)");
            }
            break;
          default:
            throw new \Exception("Unexpected binding argument type ($type)");
        }
    
        $currentPos = strpos($sqlStr, '?');
        if ($currentPos === false) {
          throw new \Exception("Cannot find binding location in Sql String for bundung parameter $binding ($iter)");
        }
    
        $sqlStr = substr($sqlStr, 0, $currentPos) . $bindingStr . substr($sqlStr, $currentPos + 1);
      }
    
      $search = ["select", "distinct", "from", "where", "and", "order by", "asc", "desc", "inner join", "join"];
      $replace = ["SELECT", "DISTINCT", "\n  FROM", "\n    WHERE", "\n    AND", "\n    ORDER BY", "ASC", "DESC", "\n  INNER JOIN", "\n  JOIN"];
      $sqlStr = str_replace($search, $replace, $sqlStr);
    
      return $sqlStr;
    }
    
    0 讨论(0)
  • 2021-01-31 16:43

    You can do something like this:

    $escapedBindings = array();
    
    foreach($query->getBindings() as $item) {$escapedBindings[] = '"'.$item.'"';}
    
    $sql_with_bindings = Str::replaceArray('?', $escapedBindings, $query->toSql());
    
    0 讨论(0)
  • 2021-01-31 16:46
    $sqlQuery = Str::replaceArray(
        '?',
        collect($query->getBindings())
            ->map(function ($i) {
                if (is_object($i)) {
                    $i = (string)$i;
                }
                return (is_string($i)) ? "'$i'" : $i;
            })->all(),
        $query->toSql());
    
    0 讨论(0)
  • 2021-01-31 16:46

    Output to the log all queries with inserted bindings sorted from the slowest query to the fastest:

        \DB::enableQueryLog();
    
        // Put here your queries 
        $query = DB::table('table')->whereIn('some_field', [1,2,30]); 
        $query2 = DB::table('table2')->where('some_field', '=', 10); 
    
    
        $logQueries = \DB::getQueryLog();
        usort($logQueries, function($a, $b) {
            return $b['time'] <=> $a['time'];
        });
    
        foreach ($logQueries as $item) {
            \Log::info(str_replace_array('?', $item['bindings'], $item['query']));
            \Log::info($item['time']. ' ms');
        }
    
    0 讨论(0)
  • 2021-01-31 16:49

    This is a very old question (2015), but since this is the first Google result I got I think it's worth to give my solution as well, in case it's useful for the next person.

    Eloquent (5.7 onwards I think, I haven't tested more recent or earlier versions) has a method to change a Builder's from to wrap a subquery:

    # Taken from Illuminate/Database/Query/Builder.php - Line 272
    public function fromSub($query, $as) {
        [$query, $bindings] = $this->createSub($query);
    
        return $this->fromRaw('('.$query.') as '.$this->grammar->wrapTable($as), $bindings);
    }
    

    This however requires an already existing instance of \Illuminate\Database\Query\Builder. In order to make an empty one, you can do:

    use Illuminate\Database\Capsule\Manager as DB;
    
    $fancy = DB::table("videogames")->where("uses_sdl2", 1);
    $empty = DB::table(null);
    
    # Wrap the fancy query and set it as the "from" clause for the empty one
    # NOTE: the alias is required
    $empty = $empty->fromSub($fancy, "performant_games");
    
    

    This will warranty that bindings are treated correctly, since they'll be handled by Eloquent itself.

    0 讨论(0)
提交回复
热议问题