注:$c = new CDbCriteria();是ActiveRecord的一種寫法,使ActiveRecord更加靈活,而不是手冊中DAO(PDO)和Query Builder。
這是Yii CDbCriteria的一些筆記和經常使用用法:
1、一個sql拼裝的狀況sql
$criteria = new CDbCriteria; 數組
$criteria->addCondition("id=1"); //查詢條件,即where id = 1 app
$criteria->addInCondition('id', array(1,2,3,4,5)); //表明where id IN (1,23,,4,5,); ui
$criteria->addNotInCondition('id', array(1,2,3,4,5));//與上面正好相法,是NOT IN spa
$criteria->addCondition('id=1','OR');//這是OR條件,多個條件的時候,該條件是OR而非AND code
$criteria->addSearchCondition('name', '分類');//搜索條件,其實表明了。。where name like '%分類%' 對象
$criteria->addBetweenCondition('id', 1, 4);//between 1 and 4 排序
$criteria->compare('id', 1); //這個方法比較特殊,他會根據你的參數自動處理成addCondition或者addInCondition, it
//即若是第二個參數是數組就會調用addInCondition io
$criteria->addCondition("id = :id");
$criteria->params[':id']=1;
//屬性方式
$criteria->select = 'id,parentid,name'; //表明了要查詢的字段,默認select='*';
$criteria->join = 'xxx'; //鏈接表
$criteria->with = 'xxx'; //調用relations
$criteria->limit = 10; //取1條數據,若是小於0,則不做處理
$criteria->offset = 1; //兩條合併起來,則表示 limit 10 offset 1,或者表明了。limit 1,10
$criteria->order = 'xxx DESC,XXX ASC' ;//排序條件
$criteria->group = 'group 條件';
$criteria->having = 'having 條件 ';
$criteria->distinct = FALSE; //是否惟一查詢
實例:
$criteria = new CDbCriteria();
$criteria->select = 'table_name,model_id,sum(amount) total';
$criteria->group = 'table_name,model_id';
$criteria->addCondition("$nIdcId=4");//也能夠$criteria->condition = "$nIdcId=4";
$aResult = accessory_info::model()->findAll($criteria);
$c = new CDbCriteria();
$c->select = 't.id, t.created_at, t.outsource_id, t.user_id, t.operate, t.content';
$c->join = 'LEFT JOIN outsource ON outsource.id=t.outsource_id';
$c->condition = 'outsource.idc_id IN(' . implode(',', $idc_ids) . ')';
if($last_log_id) {
$c->condition .= " AND t.id > $last_log_id";
}
$c->limit = 20;
$c->order = 't.id DESC';
$logs = OutsourceProcessLog::model()->findAll($c);
Yii使用findAll返回數據時對象,須要循環能夠直接按照數據形式進行遍歷。例如你返回的結果變量爲$result,那麼遍歷的時就能夠直接這麼寫:
foreach($result as $k =>$v)
{
echo '姓名:'.$v['name'];
}
我常常這麼用,Yii還提供一種查詢方式,代碼以下:
Yii::app()->db->createCommand('SELECT * FROM user)->queryAll();