# Yii `CDbCriteria` 常用方法（多條件查詢）

> 原始筆記參考：<http://blog.csdn.net/duck_arrow/article/details/10006007>

## 前言

`$c = new CDbCriteria();` 是 **ActiveRecord** 的一種寫法，讓查詢條件更靈活；與手冊中純 **DAO（PDO）** 或 **Query Builder** 的風格不同。

以下為 Yii 1.x `CDbCriteria` 的筆記與常見用法整理。

---

## 一、單一條件／SQL 片段拼裝

### 1.1 函數方式

```php
$criteria = new CDbCriteria;

// 查詢條件（WHERE）
$criteria->addCondition("id=1"); // where id = 1
$criteria->addInCondition('id', array(1, 2, 3, 4, 5)); // where id IN (1,2,3,4,5)
$criteria->addNotInCondition('id', array(1, 2, 3, 4, 5)); // NOT IN
$criteria->addCondition('id=1', 'OR'); // 與其他條件組合時為 OR（預設為 AND）
$criteria->addSearchCondition('name', '分類'); // where name LIKE '%分類%'
$criteria->addBetweenCondition('id', 1, 4); // between 1 and 4

// 依第二參數型別自動變成 addCondition 或 addInCondition（陣列則為 IN）
$criteria->compare('id', 1);

// 命名參數
$criteria->addCondition("id = :id");
$criteria->params[':id'] = 1;
```

### 1.2 屬性方式

```php
$criteria->select = 'id, parentid, name'; // 預設 select='*'
$criteria->join = 'xxx';                 // JOIN
$criteria->with = 'xxx';                 // 關聯 relations
$criteria->limit = 10;
$criteria->offset = 1;                   // 與 limit 合併解讀為 LIMIT/OFFSET
$criteria->order = 'xxx DESC, xxx ASC';
$criteria->group = '...';
```

### 1.3 實例：GROUP BY 與聚合

```php
$criteria = new CDbCriteria();
$criteria->select = 'table_name, model_id, SUM(amount) AS total';
$criteria->group = 'table_name, model_id';
$criteria->addCondition("$nIdcId = 4");
// 亦可：$criteria->condition = "$nIdcId = 4";
$aResult = Accessory_info::model()->findAll($criteria);
```

### 1.4 實例：JOIN 與條件

```php
$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);
```

### 1.5 批註

1. 與 **DAO** 直接 `queryAll` 的差異：DAO 回傳每筆為**陣列**；`CDbCriteria` + AR 多為**模型物件**。
2. 功能再強仍可能有無法表達的 SQL（例如複雜子查詢、特殊聚合），此時仍宜寫原生 SQL。
3. 除錯可看執行後的 criteria 物件內容，理解 Yii 如何組出條件。

```php
$c = new CDbCriteria();
$c->join = "JOIN idc_user ON t.id = idc_user.user_id";
$c->condition = "idc_user.idc_id = $idc_id";

// 執行前可 var_dump($c) 觀察各屬性
// User::model()->with('Idcs')->findAll($c);
```

---

## 二、`mergeWith` 在 ActiveRecord 中合併條件

在模型或行為裡可對既有 criteria 再合併條件：

```php
$this->getDbCriteria()->mergeWith(array(
    'condition' => "idc_id IN ($ids)",
));
```

---

## 三、條件方法速查（含簽名概念）

```php
$criteria = new CDbCriteria;
```

| 方法 | 說明 |
|------|------|
| `addCondition($condition, $operator = 'AND')` | 附加 WHERE 片段 |
| `addInCondition($column, $values, $operator = 'AND')` | `IN (...)` |
| `addNotInCondition($column, $values, $operator = 'AND')` | `NOT IN` |
| `addSearchCondition($column, $keyword, $escape = true, $operator = 'AND', $like = 'LIKE')` | LIKE 搜尋 |
| `compare($column, $value, $partialMatch = false, $operator = 'AND', $escape = true)` | 依參數自動處理單值／陣列 |
| `addBetweenCondition($column, $start, $end, $operator = 'AND')` | BETWEEN |

範例：

```php
$criteria->addCondition("id = :id");
$criteria->addCondition('id=1', 'OR');
$criteria->params[':id'] = 1;

$criteria->addInCondition('id', array(1, 2, 3));
$criteria->addNotInCondition('id', array(1, 2, 3));
$criteria->addSearchCondition('name', '分類');
$criteria->compare('id', 1);
$criteria->addBetweenCondition('id', 1, 4);

$criteria->select = 'id, parentid, name';
$criteria->join = 'xxx';
$criteria->with = 'xxx';
$criteria->limit = 10;
$criteria->offset = 1;
$criteria->order = 'xxx DESC, xxx ASC';
$criteria->group = '...';
$criteria->having = '...';
$criteria->distinct = false;
```

> 節錄來源標註：亮子 zl（2015）、大洋 PHP（2018）等部落格整理。

### 相關連結

- <https://blog.csdn.net/eddy23513/article/details/80340209>
- <https://blog.csdn.net/u012322925/article/details/48245861>
- Yii 1.1 官方 API：<https://www.yiichina.com/doc/api/1.1/CDbCriteria>

---

## 四、條件查詢與 `criteria` 生效的 API

### 4.1 查詢範例

```php
$criteria = new CDbCriteria;
$criteria->order = 'user_name';
$criteria->addInCondition('id', $permissions);
$criteria->addInCondition('user_name', $permissions, 'OR');
$accountModels = (new Ebay())->findAll($criteria);

$criteria = new CDbCriteria;
$criteria->distinct = false;
$criteria->addCondition("id=1");
$criteria->addInCondition('id', array(1, 2, 3, 4, 5));
$criteria->addNotInCondition('id', array(1, 2, 3, 4, 5));
$criteria->addCondition('id=1', 'OR');
$criteria->addSearchCondition('name', '分類');
$criteria->addBetweenCondition('id', 1, 4);
```

下列方法會讓 `CDbCriteria` 的屬性（如 `condition`、`params`）生效：

- `CActiveRecord::find()`
- `CActiveRecord::findAll()`
- `CActiveRecord::findByPk()`
- `CActiveRecord::findAllByPk()`
- `CActiveRecord::findByAttributes()`
- `CActiveRecord::findAllByAttributes()`
- `CActiveRecord::count()`

### 4.2 更新相關

```php
$update = Yii::app()->db->createCommand()
    ->update('tbl_post', array('star' => 'star + 1', 'total' => 'total + ' . $ratingAjax),
        'id=:id', array(':id' => $post_id));

Post::model()->updateAll($attributes, $condition, $params);
Post::model()->updateByPk($pk, $attributes, $condition, $params);
Post::model()->updateCounters($counters, $condition, $params);
```

實例：

```php
$link = Enewslink::model();
$link->updateAll(array('onclick' => '200'), 'lid=:lid', array(':lid' => '1'));

Admin::model()->updateByPk(1, array('username' => 'admin', 'password' => 'admin'));
Admin::model()->updateByPk(
    array(1, 2),
    array('username' => 'admin', 'password' => 'admin'),
    'username=:name',
    array(':name' => 'admin')
);
```

---

## 五、CGridView 內建 JavaScript（jQuery）

**目錄概念：** 更新 grid、取列、取欄、目前選取、列 key、grid URL。

```php
$this->widget('zii.widgets.grid.CGridView', array(
    'id' => 'my-grid',
    'dataProvider' => $dp,
    'columns' => array(
        // ...
    ),
));
```

常用呼叫（Yii 1.x）：

```javascript
$.fn.yiiGridView.update('my-grid');
// 或
$('#my-grid').yiiGridView('update');

$.fn.yiiGridView.getRow(row_number);
$.fn.yiiGridView.getColumn(column_number);
$.fn.yiiGridView.getSelection('my-grid');
$.fn.yiiGridView.getKey(row_number);
$.fn.yiiGridView.getUrl('my-grid');
```

表格結尾會有 class 為 `keys` 的 `div` 存放各列主鍵。

```javascript
var key = $("#my-grid").yiiGridView('getKey', 5); // 第 6 列（0-based）
```

帶參數更新範例：

```javascript
$.fn.yiiGridView.update('app-list', {
    data: { seriesDel: [1, 2, 3] },
    success: function (data) {
        alert('ok');
    },
});

$.fn.yiiGridView.update('app-list', {
    data: { seriesDel: [1, 2, 3] },
    complete: function (jqXHR, status) {
        if (status === 'success') {
            console.log(jqXHR, status);
        }
    },
});
```

---

## 六、`rules()` 與模型驗證範例

```php
public function rules()
{
    return array(
        array('logo', 'file', 'types' => 'jpg, jpeg, gif, png', 'on' => 'first_step'),
    );
}
```

泛用結構：

```php
public function rules()
{
    return array(
        array(
            'attribute list',
            'validator name',
            'on' => 'scenario name',
            'message' => "The attribute didn't validate!",
            // 其他驗證參數…
        ),
        array('username, password', 'required'),
        array('password_repeat', 'required', 'on' => 'register'),
        array('password', 'compare', 'compareAttribute' => 'password_repeat', 'on' => 'register'),
    );
}
```

自訂驗證：

```php
public function rules()
{
    return array(
        array('password', 'validateLogin'),
        array('username, password', 'required'),
        array('username', 'ext.MyValidators.MyLoginValidator'),
    );
}

// public function validateLogin() { ... }
```

情境（scenario）：

```php
$modelA = User::model()->findByPk(1); // scenario 常為 update
$modelB = new User();
$modelB->scenario = 'light';
if ($modelB->validate()) {
    // ...
}
```

數值／費率範例（節錄）：

```php
public function rules()
{
    return array(
        array('logistics_id', 'required'),
        array('logistics_id, created_by, updated_by', 'numerical', 'integerOnly' => true),
        array(
            'bid_percentage', 'numerical', 'allowEmpty' => false, 'min' => 1, 'max' => 100,
            'numberPattern' => '/^\s*[0-9]+(\.?(\d){0,1})$/',
            'message' => '費率只能是一位小數的數字',
            'on' => 'updatebidpercentage',
        ),
        array(
            'adjustable_rate', 'numerical', 'allowEmpty' => false, 'min' => 0, 'max' => 1,
            'numberPattern' => '/^\s*[0-1]+(\.?(\d){0,3})$/',
            'message' => '傭金比例只能是小於 1 的 3 位小數',
        ),
        array('created_date, updated_date', 'safe'),
        array(
            'id, logistics_id, sky_shipping_cost, exchange_rate_usd_to_cny, exchange_rate_cny_to_usd, pack_volume_multiple, domestic_trip_cost, adjustable_rate, created_by, updated_by, created_date, updated_date, remark',
            'safe',
            'on' => 'search',
        ),
    );
}
```

---

## 七、PDO `fetch` 模式與 `CDbCommand`

```php
$command = Yii::app()->db->createCommand($sql);
$command->setFetchMode(PDO::FETCH_OBJ);
$command->execute($params);
return $command->queryAll();
```

- `PDO::FETCH_ASSOC`：關聯陣列  
- `PDO::FETCH_NUM`：數字索引  
- `PDO::FETCH_BOTH`：兩者皆有（常見預設）  
- `PDO::FETCH_OBJ`：物件  
- `PDO::FETCH_BOUND`：與 `bindParam` 綁定欄位  
- `PDO::FETCH_LAZY`：關聯／數字／物件延遲載入式存取  

---

## 八、動態組 WHERE 範例

```php
$where = array();
$params = array();
$where_str = 'WHERE 0';

if (count($params) > 0) {
    foreach ($params as $key => $val) {
        $where[] = $key . '=:' . $key;
        $params[':' . $key] = $val;
    }
}
if (count($where) > 0) {
    $where_str = 'WHERE ' . implode(' AND ', $where);
}

$sql = "SELECT * FROM ref_name {$where_str} ORDER BY rn_Sort";
$rawData = array();
$Command = Yii::app()->db->createCommand($sql);
$Command->execute($params);
return $Command->queryAll();
```

（註：原筆記中 `$where` 變數在 `implode` 處應為 `$where` 陣列；若邏輯上要從 `$params` 建條件，需依實際專案調整迴圈來源。）

---

## 九、較完整的 `rules()` 註冊範例（節錄）

```php
public function rules()
{
    return array(
        array('email, username, password, agree, verifyPassword, verifyCode', 'required'),
        array('email', 'unique', 'message' => '使用者名稱已佔用'),
        array('email, username', 'length', 'max' => 64),
        array('username', 'length', 'max' => 7, 'min' => 2,
            'tooLong' => '使用者名稱請輸入長度為 4-14 個字元',
            'tooShort' => '使用者名稱請輸入長度為 2-7 個字'),
        array('password', 'length', 'max' => 22, 'min' => 6,
            'tooLong' => '密碼請輸入長度為 6-22 位字元',
            'tooShort' => '密碼請輸入長度為 6-22 位字元'),
        array('email', 'email', 'message' => '郵箱格式錯誤'),
        array('verifyPassword', 'compare', 'compareAttribute' => 'password', 'message' => '請再輸入確認密碼'),
        array('agree', 'required', 'requiredValue' => true, 'message' => '請確認是否同意隱私權協議條款'),
        array('created', 'date', 'format' => 'yyyy/MM/dd HH:mm:ss'),
        array('superuser', 'in', 'range' => array(0, 1)),
        array('name', 'match', 'pattern' => '/^[a-z0-9\-_]+$/'),
        array('id', 'numerical', 'min' => 1, 'max' => 10, 'integerOnly' => true),
        array('created', 'type', 'datetime'),
        array('filename', 'file', 'allowEmpty' => true, 'types' => 'zip, rar, xls, pdf, ppt', 'tooLarge' => '圖片不要超過 800K'),
        array(
            'url',
            'file',
            'allowEmpty' => true,
            'types' => 'jpg,png,gif,doc,docx,pdf,xls,xlsx,zip,rar,ppt,pptx',
            'maxSize' => 1024 * 1024 * 10,
            'tooLarge' => '檔案大於 10M，上傳失敗！請上傳小於 10M 的檔案！',
        ),
    );
}

$news = new News('search'); // 與 scenario `search` 搭配 safe 規則
```

---

## 十、驗證器別名速覽（Yii 文檔整理）

| 別名 | 說明 |
|------|------|
| `boolean` | 布林值 |
| `captcha` | 驗證碼 |
| `compare` | 與另一屬性或常數比較 |
| `email` | 電子郵件 |
| `default` | 預設值 |
| `exist` | 存在於指定資料表欄位 |
| `file` | 上傳檔 |
| `filter` | 以 filter 轉換屬性 |
| `in` | 值在指定範圍內 |
| `length` | 字串長度 |
| `match` | 正則 |
| `numerical` | 數字 |
| `required` | 必填 |
| `type` | 型別（integer、float、string、array、date、time、datetime 等） |
| `unique` | 唯一 |
| `url` | URL |

> 規則陣列中前兩個元素通常為「屬性列表」「驗證器名稱」；`message` 為錯誤提示。

### 10.1 `required`（CRequiredValidator）

範例：`array('name', 'required', 'requiredValue' => '張', 'strict' => true, 'message' => '請填寫姓名')`

- `requiredValue`：要求的值（mixed）  
- `strict`：是否嚴格比較（boolean）  

### 10.2 `filter`（CFilterValidator）

範例：`array('name', 'test', 'message' => '請填寫姓名')`，其中 `test` 為自訂方法。

### 10.3 `match`（CRegularExpressionValidator）

範例：`array('name', 'match', 'allowEmpty' => true, 'not' => true, 'pattern' => '/[a-z]/i', 'message' => '…')`

- `allowEmpty`、`not`、`pattern`  

### 10.4 `email`（CEmailValidator）

可搭配 `allowEmpty`、`pattern`、`allowName`、`checkMx` 等。

### 10.5 `url`（CUrlValidator）

可搭配 `allowEmpty`、`pattern`、`defaultScheme`、`validSchemes` 等。

### 10.6 `unique`（CUniqueValidator）

可搭配 `allowEmpty`、`caseSensitive` 等。

### 10.7 `compare`（CCompareValidator）

- 與常數比：`compareValue`、`operator`  
- 與另一屬性比：`compareAttribute`  
- `strict`：值與型別皆需相等  

### 10.8 `length`（CStringValidator）

- `max`、`min`、`is`、`tooLong`、`tooShort`、`encoding`、`allowEmpty`  

### 10.9 `in`（CRangeValidator）

- `range`（array）、`not`、`strict`、`allowEmpty`  

### 10.10 `numerical`（CNumberValidator）

- `integerOnly`、`integerPattern`、`numberPattern`、`min`、`max`、`tooBig`、`tooSmall`、`allowEmpty`  

### 10.11 `captcha`（CCaptchaValidator）

- `caseSensitive`、`allowEmpty`  

### 10.12 `type`（CTypeValidator）

- `type`：`'string'`, `'integer'`, `'float'`, `'array'`, `'date'`, `'time'`, `'datetime'`  
- `dateFormat`、`datetimeFormat`、`timeFormat`  

### 10.13 `file`（CFileValidator）

- `types`、`maxSize`、`minSize`、`maxFiles`、`allowEmpty`、`tooLarge`、`tooMany`、`tooSmall`、`wrongType`  

### 10.14 `default`（CDefaultValueValidator）

- `setOnEmpty`、`value`  

### 10.15 `exist`（CExistValidator）

- `allowEmpty`、`attributeName`、`className`、`criteria`  

### 10.16 `boolean`（CBooleanValidator）

範例：`array('name', 'boolean', 'trueValue' => '1', 'falseValue' => '-1', 'message' => '該值只能為 1 或 -1')`

- `trueValue`、`falseValue`、`strict`、`allowEmpty`  

---

## 附註

- 本文由原 `.txt` 筆記整理為 Markdown，章節與程式區塊已重新編排；**Yii 版本以 1.x 為主**。  
- 若你主要使用 **Yii 2**，對應類別為 `yii\db\ActiveQuery` 等，API 名稱與本檔不同，請改查 Yii2 官方文件。
