php 获取在 Laravel 中执行的查询 3/4

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14536165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:28:31  来源:igfitidea点击:

Get the Query Executed in Laravel 3/4

phplaravelormeloquentlaravel-query-builder

提问by Patrick Maciel

How can I retrieve the raw executed SQL query in Laravel 3/4 using Laravel Query Builder or Eloquent ORM?

如何使用 Laravel Query Builder 或 Eloquent ORM 在 Laravel 3/4 中检索原始执行的 SQL 查询?

For example, something like this:

例如,这样的事情:

DB::table('users')->where_status(1)->get();

Or:

或者:

(posts (id, user_id, ...))

User::find(1)->posts->get();

Otherwise, at the very least how can I save all queries executed to laravel.log?

否则,至少如何将执行的所有查询保存到 laravel.log?

回答by rmobis

Laravel 4+

Laravel 4+

In Laravel 4 and later, you have to call DB::getQueryLog()to get all ran queries.

在 Laravel 4 及更高版本中,您必须调用DB::getQueryLog()以获取所有已运行的查询。

$queries = DB::getQueryLog();
$last_query = end($queries);

Or you can download a profiler package. I'd recommend barryvdh/laravel-debugbar, which is pretty neat. You can read for instructions on how to install in their repository.

或者您可以下载分析器包。我推荐barryvdh/laravel-debugbar,它非常简洁。您可以阅读有关如何在其存储库中安装的说明。

Note for Laravel 5 users:You'll need to call DB::enableQueryLog()before executing the query. Either just above the line that runs the query or inside a middleware.

Laravel 5 用户注意事项:您需要DB::enableQueryLog()在执行查询之前调用。要么在运行查询的行上方,要么在中间件内部。



Laravel 3

Laravel 3

In Laravel 3, you can get the last executed query from an Eloquentmodel calling the static method last_queryon the DBclass.

在 Laravel 3 中,您可以从Eloquent调用类last_query上的静态方法的模型中获取最后执行的查询DB

DB::last_query();

This, however, requires that you enable the profileroption in application/config/database.php. Alternatively you could, as @dualed mentioned, enable the profileroption, in application/config/application.phpor call DB::profile()to get all queries ran in the current request and their execution time.

然而,这需要您启用profiler的选项application/config/database.php。或者,正如@dualed 所提到的,您可以启用该profiler选项,在application/config/application.php或调用DB::profile()以获取在当前请求中运行的所有查询及其执行时间。

回答by dualed

You can enable the "Profiler" in Laravel 3 by setting

您可以通过设置在 Laravel 3 中启用“ Profiler

'profiler' => true,

In your application/config/application.phpand application/config/database.php

在你application/config/application.phpapplication/config/database.php

This enables a bar at the bottom of each page. One of its features is listing the executed queries and how long each one took.

这会在每个页面的底部启用一个栏。它的功能之一是列出执行的查询以及每个查询花费的时间。

enter image description here

在此处输入图片说明

回答by JamesPlayer

For Eloquent you can just do:

对于 Eloquent,您可以这样做:

$result->getQuery()->toSql();

But you need to remove the "->get()" part from your query.

但是您需要从查询中删除“->get()”部分。

回答by Znarkus

I would recommend using the Chrome extension Clockworkwith the Laravel package https://github.com/itsgoingd/clockwork. It's easy to install and use.

我建议将 Chrome 扩展Clockwork与 Laravel 包https://github.com/itsgoingd/clockwork 一起使用。它易于安装和使用。

Clockwork is a Chrome extension for PHP development, extending Developer Tools with a new panel providing all kinds of information useful for debugging and profiling your PHP scripts, including information on request, headers, GET and POST data, cookies, session data, database queries, routes, visualisation of application runtime and more. Clockwork includes out of the box support for Laravel 4 and Slim 2 based applications, you can add support for any other or custom framework via an extensible API.

Clockwork 是一个用于 PHP 开发的 Chrome 扩展,它通过一个新面板扩展了开发者工具,提供了对调试和分析 PHP 脚本有用的各种信息,包括关于请求、标题、GET 和 POST 数据、cookie、会话数据、数据库查询的信息,路线,应用程序运行时的可视化等等。Clockwork 包括对基于 Laravel 4 和 Slim 2 的应用程序的开箱即用支持,您可以通过可扩展的 API 添加对任何其他或自定义框架的支持。

enter image description here

在此处输入图片说明

回答by Ricardo Rossi

Since the profiler is not yet out in Laravel 4, I've created this helper function to see the SQL being generated:

由于分析器尚未在Laravel 4 中推出,我创建了这个辅助函数来查看生成的 SQL:

    public static function q($all = true) 
    {
        $queries = DB::getQueryLog();

        if($all == false) {
            $last_query = end($queries);
            return $last_query;
        }

        return $queries;
    }

NOTE: Set the $allflag to falseif you only want the last SQL query.

注意:如果您只需要最后一个 SQL 查询,请将$all标志设置为false

I keep this sort of functions in a class called DBH.php (short for Database Helper) so I can call it from anywhere like this:

我将这类函数保存在一个名为 DBH.php(Database Helper 的缩写)的类中,这样我就可以像这样从任何地方调用它:

dd(DBH::q()); 

Here is the output I get: enter image description here

这是我得到的输出: 在此处输入图片说明

In case you are wondering, I use Kint for the dd() formatting. http://raveren.github.io/kint/

如果您想知道,我使用 Kint 进行 dd() 格式设置。 http://raveren.github.io/kint/

回答by Adam

Here is a quick Javascript snippet you can throw onto your master page template. As long as it's included, all queries will be output to your browser's Javascript Console. It prints them in an easily readable list, making it simple to browse around your site and see what queries are executing on each page.

这是一个快速的 Javascript 片段,您可以将其放入母版页模板。只要包含它,所有查询都会输出到您浏览器的 Javascript 控制台。它将它们打印在一个易于阅读的列表中,从而可以轻松浏览您的站点并查看每个页面上正在执行的查询。

When you're done debugging, just remove it from your template.

完成调试后,只需将其从模板中删除即可。

<script type="text/javascript">
    var queries = {{ json_encode(DB::getQueryLog()) }};
    console.log('/****************************** Database Queries ******************************/');
    console.log(' ');
    queries.forEach(function(query) {
        console.log('   ' + query.time + ' | ' + query.query + ' | ' + query.bindings[0]);
    });
    console.log(' ');
    console.log('/****************************** End Queries ***********************************/');
</script>

回答by misaizdaleka

For Laraver 4 it's

对于 Laraver 4,它是

DB::getQueryLog()

回答by Bryan

Laravel 5

Laravel 5

Note that this is the proceduralapproach, which I use for quick debugging

请注意,这是我用于快速调试的过程方法

    DB::enableQueryLog();

    // Run your queries
    // ...

    // Then to retrieve everything since you enabled the logging:
    $queries = DB::getQueryLog();
    foreach($queries as $i=>$query)
    {
        Log::debug("Query $i: " . json_encode($query));
    }

in your header, use:

在您的标题中,使用:

     use DB;
     use Illuminate\Support\Facades\Log;

The output will look something like this (default log file is laravel.log):

输出看起来像这样(默认日志文件是laravel.log):

[2015-09-25 12:33:29] testing.DEBUG: Query 0: {"query":"select * from 'users' where ('user_id' = ?)","bindings":["9"],"time":0.23}

[2015-09-25 12:33:29] testing.DEBUG: 查询 0: {"query":"select * from 'users' where ('user_id' = ?)","bindings":["9"] ,"时间":0.23}

***I know this question specified Laravel 3/4 but this page comes up when searching for a general answer. Newbies to Laravel may not know there is a difference between versions. Since I never see DD::enableQueryLog()mentioned in any of the answers I normally find, it maybe specific to Laravel 5 - perhaps someone can comment on that.

***我知道这个问题指定了 Laravel 3/4,但是在搜索一般答案时会出现这个页面。Laravel 的新手可能不知道版本之间存在差异。由于我从未DD::enableQueryLog()在我通常找到的任何答案中看到提及,因此它可能特定于 Laravel 5 - 也许有人可以对此发表评论。

回答by SnapShot

You can also listen for query events using this:

您还可以使用以下方法侦听查询事件:

DB::listen(function($sql, $bindings, $time)
{
    var_dump($sql);
});

See the information from the docs hereunder Listening For Query Events

请参阅从文档中的信息在这里监听查询活动

回答by omar j

Using the query log doesnt give you the actual RAW query being executed, especially if there are bound values. This is the best approach to get the raw sql:

使用查询日志不会为您提供正在执行的实际 RAW 查询,尤其是在存在绑定值的情况下。这是获取原始 sql 的最佳方法:

DB::table('tablename')->toSql();

or more involved:

或更多参与:

$query = Article::whereIn('author_id', [1,2,3])->orderBy('published', 'desc')->toSql();
dd($query);