在Yii的Model里進行查詢的時候 where是必不可少的。
Where方法聲明為
- static where( $condition )
其中參數 $condition類型為字符串或者數組
1、字符串
字符串是最簡單的,直接按sql中的where條件寫就可以,如
- $condition = 'name=\'zhidemy.com\' and age>10';
2、數組
如果是數組的情況下,有兩種格式的寫法。
- name-value格式的字典數組:['column1' => value1, 'column2' => value2, ...]
- 邏輯操作符格式:[operator, operand1, operand2, ...]
第一種寫法:
如果value值是字符串或者數字等,那么生成的條件語句格式為column1=value1 AND column2=value2 AND ....
['type' => 1, 'status' => 2]
//生成
(type = 1) AND (status = 2)
如果value值是數組,那么會生成sql 中的IN語句;
['id' => [1, 2, 3], 'status' => 2]
//生成
(id IN (1, 2, 3)) AND (status = 2)
如果value值為Null,那么會生成 Is Null語句。
['status' => null]
//生成
status IS NULL
第二種寫法會根據不同的操作符生成不同的sql條件。
- and: 會使用 AND把所有的操作數連接起來。如
['and', 'id=1', 'id=2']
// 生成
id=1 AND id=2
['and', 'type=1', ['or', 'id=1', 'id=2']]
//生成
type=1 AND (id=1 OR id=2)
- or: 和 and 類似,只不過是用 OR來連接操作數。
- between: 第一個操作數是列的名稱,第二個和第三個操作數為范圍的最小值和最大值。如
['between', 'id', 1, 10]
//生成
id BETWEEN 1 AND 10
- not between: 和between 相似。
- in: 第一個操作數為列或者DB表達式,第二個操作數為數組, 如
['in', 'id', [1, 2, 3]]
//生成
id IN (1, 2, 3)
- not in: 和上面的in 相似。
- like: 第一個操作數為列或者DB表達式,第二個操作數為字符串或者數組如
['like', 'name', 'tester']
//生成
name LIKE '%tester%'
['like', 'name', ['test', 'sample']]
//生成
name LIKE '%test%' AND name LIKE '%sample%'
有時候你可能需要自己來處理%,那么可以用第三個參數:['like', 'name', '%tester', false]
//生成
name LIKE '%tester'
- or like: 和like相似,只是在第二個參數為數組的情況下用or來連接多個like 語句。
- not like: 和like 相似。
- or not like: 和or like 相似。