在Yii的Model里进行查询的时候 where是必不可少的。
Where方法声明为
- static where( $condition )
其中参数 $condition类型为字符串或者数组
1、字符串
字符串是最简单的,直接按sql中的where条件写就可以,如
- $condition = 'name=\'xiaoming\' and age>10';
2、数组
如果是数组的情况下,有两种格式的写法。
第一种写法:
如果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', 'type=1', ['or', 'id=1', 'id=2']]
- //生成
- type=1 AND (id=1 OR id=2)
- ['and', 'id=1', 'id=2']
- // 生成
- id=1 AND id=2
- ['between', 'id', 1, 10]
- //生成
- id BETWEEN 1 AND 10
- ['in', 'id', [1, 2, 3]]
- //生成
- id IN (1, 2, 3)
- ['like', 'name', ['test', 'sample']]
- //生成
- name LIKE '%test%' AND name LIKE '%sample%'
- ['like', 'name', '%tester', false]
- //生成
- name LIKE '%tester'
- ['like', 'name', 'tester']
- //生成
- name LIKE '%tester%'