Saturday, May 4, 2013

Yii Examples of Using CDbCriteria

Basic Usage
$Criteria = new CDbCriteria();
$Criteria->condition = "price > 30";
$Products = Product::model()->findAll($Criteria);
OR
//An example using the constructor to populate the properties.
$Criteria = new CDbCriteria(array('condition' => 'price > 30'));
$Products = Product::model()->findAll($Criteria);
Personally, I like to go with the first approach. I think it’s generally easier to read, but that’s just my personal preference.
Adding A Limit
$Criteria = new CDbCriteria();
$Criteria->condition = "price > 30";
$Criteria->limit = 1;
$Products = Product::model()->findAll($Criteria);
Limit with Offset
$Criteria = new CDbCriteria();
$Criteria->condition = "price > 30";
$Criteria->limit = 1;
$Criteria->offset = 1;
$Products = Product::model()->findAll($Criteria);
Ordering Results
$Criteria = new CDbCriteria();
$Criteria->condition = "price > 30";
$Criteria->limit = 1;
$Criteria->offset = 1;
$Criteria->order = "name ASC";
$Products = Product::model()->findAll($Criteria);
Limiting Selected Fields
$Criteria = new CDbCriteria();
$Criteria->condition = "price > 30";
$Criteria->limit = 1;
$Criteria->offset = 1;
$Criteria->order = "name ASC";
$Criteria->select = "id, name";
$Products = Product::model()->findAll($Criteria);
Example relation with :
$criteria = new CDbCriteria;
/* You can use condition as first parameter and must one conditions,
which will make and conditions with other compare values  */
$criteria->conditions = 'is_user_deleted = 0 OR is_user_deleted = 2'; 
 
$criteria->with = array('groupGroup');
$criteria->together = true; // ADDED THIS
$criteria->compare( 'groupGroup.id', $this->group_id, true ); 
/* true means compare as like '% value %' */
$criteria->compare('first_name',$this->first_name,true);
$criteria->compare('last_name',$this->last_name,true);
$criteria->order = 'first_name ASC';
$criteria->limit = 10;
If two table has same column, then need to modify some code suppose-
1. $criteria->compare($this->getTableAlias().'.deleted','0',true);
Here both this table and 'group' table has same column named 'deleted', but now 
only compare with current tables 'deleted' field. 
And foreign table must be in relations...
public function relations() {
    return array(
         'groupGroup' => array(self::BELONGS_TO, 'Group', 'group_id')
        /* group_id is current models foreign key from 'group' table. */
     );
}

No comments:

Post a Comment