Yii CActiveModel filter 搜索

Yii 列表做關聯搜索

單個屬性的搜索,Model聲明屬性,Search添加條件,Controller 賦值搜索,略顯繁瑣

class Product extends GxActiveRecord {
	// ...
	
	// Category filter
	public $category_id;
	
	// ...
	
	public function search() {
		$criteria = new CDbCriteria;
		
		// ...
		
		// Category filter
		$criteria->compare('product2categories.category_id', $this->category_id, false);
		
		// ...
		
		return new CActiveDataProvider($this, array(
			'criteria' => $criteria,
			// ...
		));
	}
}

class ProductController extends GxController {

	// ...

	public function actionIndex($category_id = 0) {
		$model = new Product('search');
		$model->unsetAttributes();
		
		// ...
		
		if($category_id){
			$model->category_id = (int)$category_id;
		}
		
		// ...
		
		$this->render('index', array(
			'model' => $model,
			'category_id' => $category_id,
			// ...
		));
	}
}

// view ....

簡單點就把整個關聯的Model直接當成屬性


class Product extends GxActiveRecord {
	// ...
	
	public $searchI18n;
	
	// ...
	
	public function search() {
		$criteria = new CDbCriteria;
		
		// ...
		
		$criteria->compare('productI18ns.title', $this->searchI18n->title, true);
		$criteria->compare('productI18ns.keywords', $this->searchI18n->keywords, true);
		$criteria->compare('productI18ns.description', $this->searchI18n->description, true);
		
		// ...
		
		return new CActiveDataProvider($this, array(
			'criteria' => $criteria,
			// ...
		));
	}
}

class ProductController extends GxController {

	// ...

	public function actionIndex($category_id = 0) {
		$model = new Product('search');
		$model->unsetAttributes();
		
		// ...
		
		$i18n = new ProductI18n('search');
		$i18n->unsetAttributes();

		$model->searchI18n = $i18n;
		
		// ...
		
		if (isset($_GET['ProductI18n'])){
			$i18n->setAttributes($_GET['ProductI18n']);
		}
		
		// ...
		
		$this->render('index', array(
			'model' => $model,
			'i18n' => $i18n,
			// ...
		));
	}
}

// view ....
// Yii version 1.1.14


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章