获取 Laravel Eloquent 查询并绑定到位

Get Laravel Eloquent query with bindings in place

当我 dd(\DB::getQueryLog()) 时,我得到如下内容:

array (size=3)
      'query' => string 'select * from `clicks` where `clicks`.`user_id` in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) and `created_at` between ? and ?' (length=114)
      'bindings' => 
        array (size=12)
          0 => int 70
          1 => int 69
          2 => int 68
          3 => int 67
          4 => int 66
          5 => int 65
          6 => int 64
          7 => int 63
          8 => int 60
          9 => int 58
          10 => 
            object(Carbon\Carbon)[681]
              public 'date' => string '2014-12-27 20:06:39.000000' (length=26)
              public 'timezone_type' => int 3
              public 'timezone' => string 'UTC' (length=3)
          11 => 
            object(Carbon\Carbon)[684]
              public 'date' => string '2015-01-26 20:06:39.000000' (length=26)
              public 'timezone_type' => int 3
              public 'timezone' => string 'UTC' (length=3)
      'time' => float 932.67

如何获得所有绑定都已到位的查询,这样我就可以将其复制到 MySQL Workbench 并修改它,而不必每次都手动添加这些绑定?

实际的 SQL 字符串在 PHP 端永远不可用。您可以尝试手动解决问题并将 ? 替换为绑定:

echo vsprintf(str_replace('?', '%s', $queryString), $bindings);

I made a function in my controller to do this:

public function create(Request $request){ //you are in some function of your controller
    DB::enableQueryLog(); //enable query log
      SomeModel::create($request->all()); //your query running
    $queryLog = DB::getQueryLog(); //get query log
    $this->showExecutedQueries($queryLog); //calling my function
}

My function:

public function showExecutedQueries($queryLog){
        foreach ($queryLog as $query){
            $aQuery[] = vsprintf(str_replace('?', '%s',$query['query']),$query['bindings']);
        }
        echo '<pre>'; print_r($aQuery); die();
    }

它将在数组中按顺序显示所有已执行的查询;