使用绑定获取Laravel Eloquent查询

时间:2015-01-26 20:10:24

标签: laravel laravel-4 eloquent

当我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并修改它,而不必每次都手动添加这些绑定?

2 个答案:

答案 0 :(得分:3)

实际的SQL字符串在PHP方面永远不可用。您可以尝试手动解决问题,并使用绑定替换?

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

答案 1 :(得分:0)

我在控制器中做了一个函数来做到这一点:

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
}

我的功能:

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

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