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


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

我一直在试图找出一种方法来记录来自我在Zend Framework 1中使用的Eloquent ORM的SQL查询。我遇到了以这种方式调用的getQueryLog()方法:

$queries = DB::getQueryLog();

我发现 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
    }
}

但是,我收到以下通知,它返回 NULL:Notice: Undefined property: IndexController::$queryLog in /var/www/qasystem/vendor/illuminate/database/Illuminate/Database/Connection.php on line 918 NULL

有人可以建议我如何在拉拉维尔之外使用它吗?我在网上搜索过,看不到我需要做的任何不同的事情,尽管我怀疑大多数例子都会在 Laravel 中使用。另外,Illuminate''Database''Connection 是正确的类吗?谢谢

请改用toSql方法。它将返回最终的查询命令。

有关详细信息,请参阅如何让查询生成器将其原始 SQL 查询输出为字符串?

即使有点旧 - 我只是遇到了同样的问题,使用 toSql() 对我没有帮助,因为我有多对多关系,而 Eloquent 执行了更多查询。

根据@patricus的评论,我让它像这样工作:

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