yii Cdbcriteria无法正常工作

时间:2014-09-25 06:36:43

标签: php yii

我想从两个表商店 mmm_store_services 中获取数据,除了这个

以外所有条件都正常
        if(isset($_POST['Store']['location']) && !empty($_POST['Store']['location'])){ 
        $conditions[] = ' AND t.location = '.$_POST["Store"]["location"];   
    }

这是我的所有代码

        $criteria=new CDbCriteria;

    $conditions = array();
    if(isset($_POST['Store']['category']) && !empty($_POST['Store']['category'])){
        $conditions[] = ' AND mmm_store_services.category_id ='.$_POST['Store']['category'];
    }

    if(isset($_POST['Store']['sub_category']) && !empty($_POST['Store']['sub_category'])){
        $conditions[] = ' AND mmm_store_services.service_id ='.$_POST['Store']['sub_category'];
    }

    if(isset($_POST['Store']['location']) && !empty($_POST['Store']['location'])){ 
        $conditions[] = ' AND t.location = '.$_POST["Store"]["location"];   
    }

    if(isset($_POST['Store']['price']) && !empty($_POST['Store']['price'])){
        $price = explode('-',$_POST['Store']['price']);
        $minPrice = trim($price[0]);
        $maxPrice = trim($price[1]);
        $conditions[] = ' AND mmm_store_services.price between '.$minPrice.' AND '.$maxPrice;
    }


    if(count($conditions)>0){
        $condition = implode(' ',$conditions);
        $criteria->join.='INNER JOIN mmm_store_services ON mmm_store_services.store_id = t.id '.$condition;
    }



    $criteria->compare('t.approve','Y');     
    $model = new CActiveDataProvider('Store', array(
        'criteria'=>$criteria,
        'pagination'=>array('pageSize'=>'2'),
    ));

请给我一个解决方案。 感谢。

1 个答案:

答案 0 :(得分:0)

如果您的$conditions必须在WHERE部分,而不在JOIN部分,那么您缺少WHERE关键字并且使用CDbCriteria错误(基本上根本不使用它) )。

$criteria = new CDbCriteria();
$flag = false;

if(isset($_POST['Store']['category']) && !empty($_POST['Store']['category'])){
    $criteria->addCondition(['mmm_store_services.category_id' => $_POST['Store']['category']]);
    $flag = true;
}

if(isset($_POST['Store']['sub_category']) && !empty($_POST['Store']['sub_category'])){
    $criteria->addCondition(['mmm_store_services.service_id' => $_POST['Store']['sub_category']]);
    $flag = true;
}

if(isset($_POST['Store']['location']) && !empty($_POST['Store']['location'])){ 
    $criteria->addCondition(['t.location' => $_POST["Store"]["location"]]);
    $flag = true;
}

if(isset($_POST['Store']['price']) && !empty($_POST['Store']['price'])){
    $price = explode('-',$_POST['Store']['price']);
    $minPrice = trim($price[0]);
    $maxPrice = trim($price[1]);
    $criteria->addBetweenCondition('mmm_store_services.price', $minPrice, $maxPrice);
    $flag = true;
}


if($flag){
    $criteria->with = ['mmm_store_service']; // Put `mmm_store_service` to relations of model 'Store'
    $criteria->together = true; // Check if you really need this parameter!
}

$criteria->compare('t.approve', 'Y');   

$model = new CActiveDataProvider('Store', array(
    'criteria' => $criteria,
    'pagination' => array('pageSize'=>'2'),
));