Db组件Yii 中有一个有用的方法getStats
$sql_stats = YII::app()->db->getStats();
echo $sql_stats[0] //the number of SQL statements executed
echo $sql_stats[1] //total time spent
官方文档链接
Yii2中是否有获取这些信息的方法?
这里是Yii 2的等价物:
$profiling = Yii::getLogger()->getDbProfiling();
$profiling[0]
包含数据库查询的总数,$profiling[1]
—总执行时间。
请注意,如果您想在请求结束时获得有关所有查询的信息,您应该在正确的位置执行此代码,例如在afterAction()
:中
public function afterAction($action, $result)
{
$result = parent::afterAction($action, $result);
$profiling = Yii::getLogger()->getDbProfiling();
...
return $result;
}
否则,您将根据执行此命令的时刻获得信息。
官方文档:
- getDbProfile()
- afterAction()
如果启用调试工具栏,你会得到更多的信息,这比这要好得多。此外,您还可以启用日志记录,这也会为您提供更多信息。
有关调试工具栏的详细信息,请单击此处http://www.yiiframework.com/doc-2.0/ext-debug-index.html以及有关登录的更多信息http://www.yiiframework.com/doc-2.0/guide-runtime-logging.html