Getting the string representation from CDbCriteria

醉酒当歌 提交于 2019-12-20 04:24:41

问题


Is there any way to the get the string representation of the query from CDbCriteria? For testing and debugging purposes.


回答1:


You can use logging and profiling configuring your main.php like this:

'components'=>array(
    'log'=>array(
        'class'=>'CLogRouter',
        'routes'=>array(
            array(
                'class'=>'CWebLogRoute',
                'categories'=>'system.db.CDbCommand',
                'showInFireBug'=>true,
            ),
        ),
    ),
    'db'=>array(
        'enableProfiling'=>true,
        'enableParamLogging'=>true,
    ),              
),



回答2:


I spend a lot amount of time for finding the answer to this question, so thought of sharing it with you guys. Hope this saves your precious time.

As mentioned by Jon above: CDbCriteria does not aggregate enough information to construct the full query, you have to use the model class information also on which you will put the query constraints.

As the example given in Yii docs for CDbCriteria; this is how basically you use it-

$criteria=new CDbCriteria(); 
$criteria->compare('status',Post::STATUS_ACTIVE); 
$criteria->addInCondition('id',array(1,2,3,4,5,6)); 

$posts = Post::model()->findAll($criteria);

Here Post is the name of the model on which you execute the query condition.

So if you want to get the text representation of the query written in CDbCriteria, you have to involve the model information also i.e. Post.

This is how you can do it -

$model = new Post();
$query = $model->getCommandBuilder()->createFindCommand($model->getTableSchema(), $criteria)->getText();

When you print the value in $query variable it prints the raw query.

Hope this helps.



来源:https://stackoverflow.com/questions/9895982/getting-the-string-representation-from-cdbcriteria

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!