Generate The Raw MySQL Query From Laravel Query Builder

后端 未结 14 1176
醉话见心
醉话见心 2021-02-02 12:04

How can i get mysql query of a laravel query

Convert:

App\\User::where(\'balance\',\'>\',0)->where(...)-         


        
14条回答
  •  闹比i
    闹比i (楼主)
    2021-02-02 12:43

    Here is a helper function who tells you the last SQL executed.

    use DB;
    public static function getLastSQL()
    {
        $queries = DB::getQueryLog();
        $last_query = end($queries);
              // last_query is the SQL with with data binding like 
              //   { 
              //       select ? from sometable where field = ? and field2 = ? ;
              //       param1,
              //       param2,
              //       param3,
              //   }
              //   which is hard to read.
        $last_query = bindDataToQuery($last_query);     
              // here, last_query is the last SQL you have executed as normal SQL
              //     select param1 from sometable where field=param2 and field2 = param3;
        return $last_query
    }
    

    Here is the bindDataToQuery function, who fill the '?' blanks with real params.

    protected static function bindDataToQuery($queryItem){
        $query = $queryItem['query'];
        $bindings = $queryItem['bindings'];
        $arr = explode('?',$query);
        $res = '';
        foreach($arr as $idx => $ele){
            if($idx < count($arr) - 1){
                $res = $res.$ele."'".$bindings[$idx]."'";
            }
        }
        $res = $res.$arr[count($arr) -1];
        return $res;
    }
    

提交回复
热议问题