熟悉Yii2的查詢條件後,用Active Record查詢數據很是方便。php
如下咱們介紹where()方法當中,條件的拼裝方式。數組
Yii2用where()方法(固然還有其餘方法)來實現條件篩選,語法:this
public $this where ( $condition, $params = [] )
$params爲可選參數,指定要綁定查詢的值。code
**$condition**爲必選參數,$condition能夠是字符串(如'id=1')或者數組。字符串
$condition爲數組時,有兩種格式:it
哈希格式:['column1' => value1, 'column2' => value2, ...]
運算符格式:[operator, operand1, operand2, ...]io
一般,哈希格式的查詢條件生成這樣的SQL語句:class
column1=value1 AND column2=value2 AND ...test
若是某個值是數組,就會生成IN語句。select
若是某個值爲null,會用IS NULL來生成語句。
例子:
['type' => 1, 'status' => 2] // 生成:(type = 1) AND (status = 2) ['id' => [1, 2, 3], 'status' => 2] // 生成:(id IN (1, 2, 3)) AND (status = 2) ['status' => null] // 生成:status IS NULL
在運算符格式,Yii會根據指定的運算符生成SQL語句。
運算符有:and、or、not、between、not between、in、not in、like、or like、not like、or not like、exists、not exists、>、<、=、>=、<=、!=等。
['>', 'id', 1] // 生成:id > 1 ['<', 'id', 100] // 生成:id < 100 ['=', 'id', 10] // 生成:id = 10 ['>=', 'id', 1] // 生成:id >= 1 ['<=', 'id', 100] // 生成:id <= 100 ['!=', 'id', 10] // 生成:id != 10
具體生成的SQL語句,運算符id會自動加上反斜槓引號`,運算數會自動轉義。
['and', 'id' => 1, 'id' => 2] // 生成:id=1 AND id=2 ['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)
在第2條和第3條語句中,列名稱和搜索值未用鍵值關係指定,因此生成的SQL不會添加引號,也不會轉義。
['or', ['type' => [7, 8, 9]], ['id' => [1, 2, 3]]] // 生成:(type IN (7, 8, 9) OR (id IN (1, 2, 3)))
['not', ['attribute' => null]] // 生成:NOT (attribute IS NULL)
['between', 'id', 1, 10] // 生成:id BETWEEN 1 AND 10 ['not between', 'id', 1, 10] // 生成:id NOT BETWEEN 1 AND 10
運算符後面的運算數1爲數據表列名稱,運算數2和運算數3分別爲列值範圍的最小值和最大值。
['in', 'id', [1, 2, 3]] // 生成:id IN (1, 2, 3) ['not in', 'id', [1, 2, 3]] // 生成:id NOT IN (1, 2, 3)
運算符後面的運算數1爲列名稱或DB表達式,運算數2爲數組,指定列值所在的範圍。
這個方法會爲值添加引號,並正確轉義。
要生成混合IN條件,列名和列值都設置爲數組,而且用列名爲列值指定下標:
['in', ['id', 'name'], [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]] // 生成:(`id`, `name`) IN ((1, 'foo'), (2, 'bar'))
另外,還能夠用子查詢做爲IN條件的值,以下:
['in', 'user_id', (new Query())->select('id')->from('users')->where(['active' => 1])]
['like', 'name', 'tester'] // 生成:name LIKE '%tester%' ['like', 'name', ['test', 'sample']] // 生成:name LIKE '%test%' AND name LIKE '%sample%' ['like', 'name', '%tester', false] // 生成:name LIKE '%tester' // 這是自定義查詢方式,要傳入值爲false的運算數3,而且自行添加%運算數後面的運算數1爲列名稱或DB表達式,運算數2爲字符串或數組,指定列值查詢條件。
這個方法會爲值添加引號,並正確轉義。
or like、not like、or not like用法和like同樣。
['or like', 'name', ['test', 'sample']] // 生成:name LIKE '%test%' OR name LIKE '%sample%' ['not like', 'name', 'tester'] // 生成:name NOT LIKE '%tester%' ['or not like', 'name', ['test', 'sample']] // 生成:name NOT LIKE '%test%' OR name NOT LIKE '%sample%'
['exists', (new Query())->select('id')->from('users')->where(['active' => 1])] // 生成:EXISTS (SELECT "id" FROM "users" WHERE "active"=1)
not exists用法和exists同樣。