YII, my sample model for search with relataionship

A model file for yii which has search fucntion which searches using relation ship:


* This is the model class for table "sf_category_slider".
* The followings are the available columns in table 'sf_category_slider':
* @property integer $rec_id
* @property integer $cat_id
* @property string $brand_id
* @property string $slider_image
* @property string $slider_link
class CategorySlider extends CActiveRecord {

* Returns the static model of the specified AR class.
* @return CategorySlider the static model class

public $category_name;

public static function model($className=__CLASS__) {
return parent::model($className);

* @return string the associated database table name
public function tableName() {
return 'sf_category_slider';

* @return array validation rules for model attributes.
public function rules() {
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('slider_link', 'required'),
array('cat_id', 'numerical', 'integerOnly' => true),
array('brand_id', 'length', 'max' => 50),
array('slider_link', 'length', 'max' => 255),
array('slider_image', 'file', 'types' => 'jpg, gif, png', 'allowEmpty' => true),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('rec_id, cat_id, brand_id, slider_image, slider_link, category_name', 'safe', 'on' => 'search'),

* @return array relational rules.
public function relations() {
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'cat_slider_relation_category' => array(self::BELONGS_TO, 'Category', 'cat_id'),

* @return array customized attribute labels (name=>label)
public function attributeLabels() {
return array(
'rec_id' => 'Rec',
'cat_id' => 'Category',
'brand_id' => 'Brand',
'slider_image' => 'Slider Image',
'slider_link' => 'Slider Link',

* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
public function search() {
// Warning: Please modify the following code to remove attributes that
// should not be searched.

$criteria = new CDbCriteria;

$criteria->compare('t.rec_id', $this->rec_id);
$criteria->compare('t.cat_id', $this->cat_id);
//$criteria->compare('brand_id', $this->brand_id);
$criteria->addSearchCondition('t.brand_id', $this->brand_id);


$criteria->compare('t.slider_image', $this->slider_image, true);
$criteria->compare('t.slider_link', $this->slider_link, true);

return new CActiveDataProvider($this, array(
'criteria' => $criteria,



Leave a comment

Your email address will not be published. Required fields are marked *