使用Cdbcriteria进行自定义查询

时间:2012-12-06 20:52:04

标签: yii

如何使用CDbCriteria和CActiveDataProvider执行此查询?

'SELECT * FROM tbl_post where title LIKE %'.$title.'% ORDER BY title LIKE '.$title.' DESC , title LIKE '.$title.'% DESC'

更新 最后我写了这个:

$criteria = new CDbCriteria;
                    $criteria->addCondition('title LIKE :title');                        
                    $criteria->params = array(':title'=>'%'.$title.'%',':t1'=>$title,':t2'=>$title.'%');;
                    $criteria->order='title LIKE :t1 DESC , title LIKE :t2 DESC';

但我收到了错误:

CDbCommand failed to execute the SQL statement: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens. The SQL statement executed was: SELECT COUNT(*) FROM `tbl_post` `t` WHERE title LIKE :title

2 个答案:

答案 0 :(得分:0)

尝试使用compare子句,不确定是否需要“按x排序”:

<?php
$criteria = new CDbCriteria;
$criteria->compare('title', $title, true);
$criteria->order = 'title DESC';
$dp = new CActiveDataprovider('posts', array(
  'criteria' => $criteria
));

答案 1 :(得分:0)

这可以这样实现:

    $dataProvider=new CActiveDataProvider('tbl_post', array(
    'criteria'=>array(
    'condition'=>'title LIKE % '.$title.' %',
    'order'=>'title DESC',
    ),
   ));

    $dataProvider->getData();

另请参阅:Help

感谢。