~~~
熟悉Yii2的查詢條件后,用Active Record查詢數據非常方便。
以下我們介紹where()方法當中,條件的拼裝方式。
#某個值為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
['NOT', ['type' => null]] // 生成:type IS NOT NULL
#對比
['>', 'id', 1] // 生成:id > 1
['<', 'id', 100] // 生成:id < 100
['=', 'id', 10] // 生成:id = 10
['>=', 'id', 1] // 生成:id >= 1
['<=', 'id', 100] // 生成:id <= 100
['!=', 'id', 10] // 生成:id != 10
['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)
['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
['in', 'id', [1, 2, 3]] // 生成:id IN (1, 2, 3)
['id' => [4, 8, 15]] // 生成:id IN (4, 8, 15)
['not in', 'id', [1, 2, 3]] // 生成:id NOT IN (1, 2, 3)
['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,并且自行添加%
['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)
~~~
- 目錄
- 配置
- 簡介
- 別名
- gii
- 配置項
- 模型
- 簡介
- 增刪改查
- AR和model
- 模型事件
- 場景
- query查詢
- 增刪改
- AR查詢器
- 模型關系定義
- AR模型連表查詢
- fields
- where拼接
- 模塊
- 創建模塊
- 控制器
- 表單
- 跳轉
- 響應
- 驗證器
- Action
- 組件
- url
- 分頁
- 驗證碼
- 緩存
- 文件上傳
- 預啟動組件
- 事件
- 自定義組件
- redis
- 日志
- 行為
- cookie和session
- 基礎知識
- 創建一個類
- 配置一個類
- object基類
- component組件類特性
- phpstorm無法更改php等級
- url地址美化
- 過濾器
- 請求處理
- 請求組件
- 響應組件
- header
- 用戶登錄
- 實現IdentityInterface接口
- 登錄
- 自動檢測登錄
- 獲取用戶信息
- 訪問行為追蹤
- phpstorm+postman斷點調試