Log the actual SQL query using ActiveRecord with Y

2019-01-10 22:19发布

I'm doing this:

$students = Student::find()->all();
    return $this->render('process', array('students' => $students));

and then this in the view:

foreach($students as $student)
    {
        echo $student->name . ',  ';
        echo $student->getQuizActivitiesCount(); ?> <br /> <?php
    }

i would like to see the sql query being performed. a student "has many" quiz activities, and the query performs perfectly, but i need to see the raw SQL. is this possible?

7条回答
神经病院院长
2楼-- · 2019-01-10 22:47

If you want to log all relational queries of ActiveRecord in console application all proposed methods doesn't help. They show only main SQL on active record's table, \yii\debug\Module works only in browser.

Alternative method to get all executed SQL queries is to log them by adding specific FileTarget to configuration:

'log' => [
    'targets' => [[
        ...
    ], [
        'class' => 'yii\log\FileTarget',
        'logFile' => '@runtime/logs/profile.log',
        'logVars' => [],
        'levels' => ['profile'],
        'categories' => ['yii\db\Command::query'],
        'prefix' => function($message) {
            return '';
        }
    ]]
]

UPDATE

In order to log insert/update/delete queries one should also add yii\db\Command::execute category:

'categories' => ['yii\db\Command::query', 'yii\db\Command::execute']
查看更多
登录 后发表回答