Yii - How to print SQL used by findAll

前端 未结 5 1654
庸人自扰
庸人自扰 2021-01-04 04:16

I have the following code to get some records from db

    $criteria = new CDbCriteria();
    $criteria->condition = \'t.date BETWEEN \"\'.$from_date.\'\"          


        
5条回答
  •  梦毁少年i
    2021-01-04 04:21

    • First way(Official way):
      In your main.php config file add these two parameters in your log section and you can see log messages at the end of your page or FireBug Console in your browser. do not forget to set necessary parameters in db section.

      'components' => array( 'db'=>array( 'enableProfiling'=>true, 'enableParamLogging' => true, ), 'log'=>array( 'class'=>'CLogRouter', 'routes'=>array( array( 'class'=>'CWebLogRoute', 'showInFireBug' => true, ), array( 'class'=>'CProfileLogRoute', 'levels'=>'profile', 'enabled'=>true, ), ), ), );

    • Second way:
      In your code just change the spelling of one of your columns to something incorrect and you will get an error message contains full SQL query in your error page(you should be in YII_DEBUG mode true). something like this:
      (I have changed t.date to t.wrong_date, when you refresh your page, you will see the generated SQL which was executed in your database)

    $criteria = new CDbCriteria(); $criteria->condition = 't.wrong_date BETWEEN "'.$from_date.'" AND "'.$to_date.'"'; $criteria->with = array('order'); $orders = ProductOrder::model()->findAll($criteria);

    in the both ways, have YII_DEBUG true in index.php

    defined('YII_DEBUG') or define('YII_DEBUG',true);
    

提交回复
热议问题