简体   繁体   English

如何在Laravel之外使用Eloquent ORM的getQueryLog()?

[英]How to use Eloquent ORM's getQueryLog() outside of Laravel?

I've been trying to figure out a way to log SQL queries from Eloquent ORM which I'm using within Zend Framework 1. I came across getQueryLog() method called in this manner: 我一直试图找出一种方法来记录我在Zend Framework 1中使用的Eloquent ORM中的SQL查询。我遇到了以这种方式调用的getQueryLog()方法:

$queries = DB::getQueryLog();

I found Illuminate\\Database\\Connection to contain the getQueryLog() method so I tried to do the following: 我发现Illuminate \\ Database \\ Connection包含getQueryLog()方法,所以我尝试执行以下操作:

use Illuminate\Database\Connection as DB;

class IndexController
{
    .
    .
    .
    public function indexAction()
    {
        // do stuff (e.g. fetch/update/create rows) 
        $questions = Questions::all()
        .
        .
        $queries = DB::getQueryLog();
        var_dump($queries); exit;
        .
        // render view
    }
}

However, I get the following notice, and it returns NULL: Notice: Undefined property: IndexController::$queryLog in /var/www/qasystem/vendor/illuminate/database/Illuminate/Database/Connection.php on line 918 NULL 但是,我得到以下通知,它返回NULL: Notice: Undefined property: IndexController::$queryLog in /var/www/qasystem/vendor/illuminate/database/Illuminate/Database/Connection.php on line 918 NULL

Can someone please suggest how I might use this outside of Laravel? 有人可以建议我如何在Laravel之外使用它吗? I've searched online and can't see anything that I need to do different, although I suspect most examples will be used within Laravel. 我在网上搜索过,看不到我需要做的任何事情,尽管我怀疑大多数例子都会在Laravel中使用。 Also, is Illuminate\\Database\\Connection the correct class? 另外,Illuminate \\ Database \\ Connection是正确的类吗? Thanks 谢谢

Use toSql method instead. 请改用toSql方法。 It will return you the final query command. 它将返回最终的查询命令。

See How do I get the query builder to output its raw SQL query as a string? 请参阅如何让查询构建器将其原始SQL查询作为字符串输出? for more info 了解更多信息

Even though a bit older- I just had the same issue, and using toSql() wasn't helping me as I have many-to-many relations and Eloquent executed more queries. 即使有点老 - 我只是遇到了同样的问题,并且使用toSql()并没有帮助我,因为我有多对多的关系,Eloquent执行了更多的查询。

Based on @patricus' comment I got it working like this: 根据@patricus的评论,我得到了这样的工作:

function getTheThing() {
  (new Thing())->getConnection()->enableQueryLog();
  $thing = Thing::whereUid('something')
    ->with('AnotherThing')
    ->first();
  $loggedSqls = (new Thing())->getConnection()->getQueryLog();
  var_dump($loggedSqls);
}

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

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