【问题标题】:Get Laravel Eloquent query with bindings in place使用适当的绑定获取 Laravel Eloquent 查询
【发布时间】:2015-01-26 20:10:23
【问题描述】:

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

【问题讨论】:

    标签: laravel laravel-4 eloquent


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      我在控制器中创建了一个函数来执行此操作:

      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();
          }
      

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

      【讨论】:

      • 嗨,欢迎来到 StackOverflow!请注意,这个问题已经有一个公认的答案。如果需要,请edit您的答案,以确保它改进了此问题中已经存在的其他答案。
      猜你喜欢
      • 1970-01-01
      • 2022-07-29
      • 2023-03-10
      • 2015-08-19
      • 2015-02-03
      • 2017-10-22
      • 2018-10-27
      • 1970-01-01
      • 2015-02-13
      相关资源
      最近更新 更多