【问题标题】:Yii CDbCriteria compare 2 attributes to a single valueYii CDbCriteria 将 2 个属性与单个值进行比较
【发布时间】:2013-11-08 10:05:09
【问题描述】:

您好,我是 yii 的新手,我目前正在做一个项目,但我遇到了 CDbCriteria 的问题。

我的目标查询是:

title LIKE '$_GET['search']%' OR description LIKE '$_GET['search']%'

是否有可能使用 CDbCriteria 比较获得类似的结果?

控制器动作:

public function actionClassifieds(){
    $model = new Classifieds('search');
    $model->unsetAttributes();
    if(isset($_GET['category'])){
        if( $_GET['category'] == 0 ){
            $model->classified_category_id = '';
        }else{
            $model->classified_category_id = $_GET['category'];
        }
    }
    if(isset($_GET['search'])){
        $model->title = $_GET['search'];
        $model->description = $_GET['search'];
    }
    $this->render('classifieds',array('model'=>$model));
}

我的模特:

public function search()
{
    // Warning: Please modify the following code to remove attributes that
    // should not be searched.

    $criteria=new CDbCriteria;

    $criteria->compare('classified_category_id',$this->classified_category_id);
    $criteria->compare('title',$this->title,true);
    $criteria->compare('description',$this->description,true);
    $criteria->compare('price',$this->price,true);
    $criteria->compare('timestamp',$this->timestamp);

    return new CActiveDataProvider($this, array(
        'criteria'=>$criteria,
        'pagination'=>array(
            'pageSize'=>10,
        ),
    ));
}

【问题讨论】:

    标签: php sql database yii


    【解决方案1】:

    试试:

    $criteria->condition = "title LIKE :t OR description LIKE :d";
    $criteria->params = array(
                  ':t' => trim( Yii::app()->request->getParam('search') ).'%', 
                  ':d' => trim( Yii::app()->request->getParam('search') ).'%'); 
    

    最好使用Yii::app()->request->getParam($var_name)

    更新

    $criteria->compare('classified_category_id',$this->classified_category_id);
    $criteria->compare('price',$this->price,true);
    $criteria->compare('timestamp',$this->timestamp);
    
    $criteria->addCondition("title LIKE :t OR description LIKE :d");
    $criteria->params[':t'] = $this->title;
    $criteria->params[':d'] = $this->description;
    

    【讨论】:

      猜你喜欢
      • 2014-02-20
      • 1970-01-01
      • 1970-01-01
      • 2015-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-30
      相关资源
      最近更新 更多