Alex
Alex

Reputation: 8072

Yii2 db getStats (db queries number)

There is useful method getStats in Db-component Yii

$sql_stats = YII::app()->db->getStats();
echo $sql_stats[0] //the number of SQL statements executed
echo $sql_stats[1] //total time spent

Official documentation link

Is there method in Yii2 to get this information?

Upvotes: 4

Views: 1377

Answers (2)

arogachev
arogachev

Reputation: 33538

Here is equivalent for Yii 2:

$profiling = Yii::getLogger()->getDbProfiling();

$profiling[0] contains total count of DB queries, $profiling[1] - total execution time.

Note that if you want to get information about all queries at the end of request you should execute this code in right place, for example in afterAction():

public function afterAction($action, $result)
{
    $result = parent::afterAction($action, $result);

    $profiling = Yii::getLogger()->getDbProfiling();

    ...

    return $result;
}

Otherwise you will get the information according to the moment of execution this command.

Official documentation:

Upvotes: 7

Mihai P.
Mihai P.

Reputation: 9357

If you enable the debugging toolbar you get a lot more info, it is much much better than this. Also you can enable logging that should also get you much more info.

More info on the debugging toolbar here http://www.yiiframework.com/doc-2.0/ext-debug-index.html and more info about the logging here http://www.yiiframework.com/doc-2.0/guide-runtime-logging.html

Upvotes: 0

Related Questions