简体   繁体   English

Laravel Eloquent builder查询日志

[英]Laravel Eloquent builder query log

I have made a JSON search engine for our APIs.我为我们的 API 创建了一个JSON 搜索引擎

The logic for assembling queries is as follows;组装查询的逻辑如下;

Laravel macro is made to enable search method on Eloquent models which creates an instance of the class and runs the search method: Laravel 宏用于在 Eloquent 模型上启用搜索方法,该模型创建 class 的实例并运行搜索方法:

/**
 * @var $this Builder
 */
$searcher = new Searcher($this, $request);
$searcher->search();

To keep things separated, request parameter classes which have URL query logic are instantiated dynamically and have the same query builder as a dependency.为了保持分离,具有 URL 查询逻辑的请求参数类被动态实例化,并且具有与依赖项相同的查询构建器。 Inside foreach loop the following is executed:在 foreach 循环中执行以下操作:

new $parameter($this->request, $this->builder, $this->modelConfig);

In order to see what was actually searched for, I have set the log to write the actual query and bindings为了查看实际搜索的内容,我设置了日志以编写实际的查询和绑定

Log::info('[Search] SQL: ' . $this->builder->toSql() . " Bindings: " . implode(', ', $this->builder->getBindings()));

Now the issue I'm having is that when loading related models (using ->with() in one of the request parameters ( RelationsParameter ) that I do get what I asked for, so model is loaded together with relations passed to it, however that is never reflected in the query.现在我遇到的问题是,在加载相关模型时(在我确实得到了我要求的请求参数( RelationsParameter )之一中使用->with()时,因此 model 与传递给它的关系一起加载,但是这永远不会反映在查询中。

I will always end up with SELECT * FROM table WHERE something , without the mention of the related table.我总是会得到SELECT * FROM table WHERE something ,而没有提及相关表。 Is there a way to get the underlying query as well?有没有办法获得基础查询?

You could wrap your code around Laravel's query logger:你可以将你的代码包装在 Laravel 的查询记录器周围:

\DB::connection()->enableQueryLog();
// your code
\DB::connection()->disableQueryLog();

After that, you may get the logged queries with \DB::getQueryLog() .之后,您可以使用\DB::getQueryLog()获取记录的查询。

However, if you just want to log while developing, I would use the barryvdh/laravel-debugbar package.但是,如果您只想在开发时记录,我会使用barryvdh/laravel-debugbar package。

I have been digging deeper within Laravel itself, and the answer to the question as why doesn't the toSql() method dump the relation SQL as well is because it gets compiled before eagerLoadRelations method is triggered.我一直在深入挖掘 Laravel 本身,问题的答案是,为什么toSql()方法不转储关系 SQL 以及因为它是在触发eagerLoadRelations方法之前编译的。

So currently, it is not possible to dump the whole SQL while operating with query builders.因此,目前,在使用查询构建器操作时,不可能转储整个 SQL。

What halloei suggests will dump all queries executed, however this does not help me at this point because it requires me to add the code outside my package. halloei建议将转储所有执行的查询,但这对我没有帮助,因为它需要我在 package 之外添加代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM