Skip to content

Instantly share code, notes, and snippets.

@pebriana
Last active April 28, 2022 12:34
Show Gist options
  • Save pebriana/a1ee028c8ac82d6c9f36 to your computer and use it in GitHub Desktop.
Save pebriana/a1ee028c8ac82d6c9f36 to your computer and use it in GitHub Desktop.
Yii Examples of Using CDbCriteria
<?php
//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;
$criteria->with = array('foreign_table1',
'foreign_table2',
'foreign_table2.foreign_table3');
$criteria->together = true; // ADDED THIS
$criteria->select = array('id');
$criteria->condition = "foreign_table1.col1=:col_val AND
foreign_table3.col3=:col_val2";
$criteria->params = array(':col_val' => some_val, ':col_val2' => other_val);
$criteria->order = 'foreign_table3.col5 DESC';
$criteria->limit = 10;
//= from: https://sonsonz.wordpress.com/2011/10/14/yii-examples-of-using-cdbcriteria/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment