Does Laravel's toSql() method mask ids? (column value being replaced by question mark)

前端 未结 4 1068
野的像风
野的像风 2020-12-15 23:46

I\'m trying to debug some SQL queries that I\'m doing in a testing suite. Using the following debugging code:

\\Log::debug(User::first()->jobs()->toSql         


        
4条回答
  •  隐瞒了意图╮
    2020-12-16 00:09

    In addition to @wader's answer, a 'macroable' way to get the raw SQL query with the bindings.

    1. Add below macro function in AppServiceProvider boot() method.

      \Illuminate\Database\Query\Builder::macro('toRawSql', function(){
          return array_reduce($this->getBindings(), function($sql, $binding){
              return preg_replace('/\?/', is_numeric($binding) ? $binding : "'".$binding."'" , $sql, 1);
          }, $this->toSql());
      });
      
    2. Add an alias to the Eloquent Builder.

      \Illuminate\Database\Eloquent\Builder::macro('toRawSql', function(){
          return ($this->getQuery()->toRawSql());
      });
      
    3. Then debug as usual.

      \Log::debug(User::first()->jobs()->toRawSql());
      

    Note: from Laravel 5.1 to 5.3, Since Eloquent Builder doesn't make use of the Macroable trait, cannot add toRawSql an alias to the Eloquent Builder on the fly. Follow the below example to achieve the same.

    E.g. Eloquent Builder (Laravel 5.1 - 5.3)

    \Log::debug(User::first()->jobs()->getQuery()->toRawSql());
    

提交回复
热议问题