Generate The Raw MySQL Query From Laravel Query Builder

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

How can i get mysql query of a laravel query

Convert:

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


        
相关标签:
14条回答
  • 2021-02-02 12:51

    DB::enableQueryLog(); (Query) $d= DB::getQueryLog(); print"<pre>"; print_r ($d); print"</pre>";

    you will get the mysql query that is just run.

    0 讨论(0)
  • 2021-02-02 12:52

    To get mysql query in laravel you need to log your query as

    DB::enableQueryLog();
    App\User::where('balance','>',0)->where(...)->get();
    print_r(DB::getQueryLog());
    

    Check reference : https://laravel.com/docs/5.0/database#query-logging

    0 讨论(0)
  • 2021-02-02 12:52

    There is actually no such thing in Laravel and even PHP, since PHP internally sends the parameters with query string to the database where it (possibly) become parsed into raw query string.

    The accepted answer is actually optimistic solution, kind of "optionally works".

    0 讨论(0)
  • 2021-02-02 12:55

    A simple way to display all queries used in Laravel without any code changes at all is to install the LaravelDebugBar (https://laravel-news.com/laravel-debugbar).

    As part of the functionality you get a tab which will show you all of the queries that a page has used.

    0 讨论(0)
  • 2021-02-02 12:56

    you can add this function to your helpers

    function getRealQuery($query, $dumpIt = false)
    {
        $params = array_map(function ($item) {
            return "'{$item}'";
        }, $query->getBindings());
        $result = str_replace_array('\?', $params, $query->toSql());
        if ($dumpIt) {
            dd($result);
        }
        return $result;
    }
    

    and use like this:

    getRealQuery(App\User::where('balance','>',0)->where(...),true)
    
    0 讨论(0)
  • 2021-02-02 13:02

    Try this:

    $results = App\User::where('balance','>',0)->where(...)->toSql();
    dd($results);
    

    Note: get() has been replaced with toSql() to display the raw SQL query.

    0 讨论(0)
提交回复
热议问题