【问题标题】:How to use Eloquent ORM's getQueryLog() outside of Laravel?如何在 Laravel 之外使用 Eloquent ORM 的 getQueryLog()?
【发布时间】:2015-03-15 21:45:21
【问题描述】:

我一直在试图找出一种方法来记录我在 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 之外使用它吗?我在网上搜索过,看不到我需要做的任何不同的事情,尽管我怀疑大多数示例将在 Laravel 中使用。另外, Illuminate\Database\Connection 是正确的类吗?谢谢

【问题讨论】:

  • 这个工作Capsule::getQueryLog()吗?
  • 你使用的是哪个版本的 laravel?
  • Capsule::getQueryLog() 不起作用。我没有使用 Laravel,我在 Zend Framework (1) 中使用 Eloquent。
  • Questions::getConnection()->getQueryLog() 工作吗?
  • 你有什么工作吗?试图找到相同的!

标签: php laravel eloquent


【解决方案1】:

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

更多信息请见How do I get the query builder to output its raw SQL query as a string?

【讨论】:

    【解决方案2】:

    即使年纪大了点——我也遇到了同样的问题,使用 toSql() 并没有帮助我,因为我有多对多关系,并且 Eloquent 执行了更多查询。

    基于@patricus'comment 我得到了它的工作原理:

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

    【讨论】:

    • 这对我使用 Illuminate\Database 8.7.1 非常有用
    猜你喜欢
    • 1970-01-01
    • 2015-03-14
    • 1970-01-01
    • 1970-01-01
    • 2013-07-07
    • 2019-03-31
    • 1970-01-01
    • 2013-01-22
    • 2015-02-02
    相关资源
    最近更新 更多