官方文档:http://www.yiichina.com/doc/guide/2.0/db-query-builder
文章涉及where、 addParams 、filterWhere 、andWhere、orWhere、 andFilterWhere()、 orFilterWhere()、andFilterCompare()
但是格式是一样的
1 2 3 |
字符串格式'status=1' 哈希格式'status' => 1, 'type' => 2] 操作符格式'like', 'name', 'test'] |
字符串和哈希格式很好理解,我们来看看操作符格式,因为操作符格式可以组成相对复杂的查询语句
最简单的就是官方给的例子
1 2 3 4 5 6 7 8 9 |
$status = 10; $search = 'yii'; $query->where(['status' => $status]); if (!empty($search)) { $query->andWhere(['like', 'title', $search]); } 生成的语句就是10) AND (`title` LIKE '%yii%') |
操作符格式
1 |
[操作符作符, 操作数1, 操作数2, ...] |
第一个参数是操作符
操作符包括and、or、 like、in、 between等
第二个第三个都是操作数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
第一种最简单的就是上面提到的例子 andWhere(['like', 'title','搜索的标题']); 生成的语句 ... WHERE (`status` = 10) AND (`title` LIKE '%yii%') 第二种二种 addWhere(['and', 'id=1', 'name=2']); 生成的语句 ... WHERE id=1 AND name=2 第三种三种 addWhere(['and', 'type=1', ['or', 'id=1', 'id=2']]); 生成的语句 ... WHERE type=1 AND (id=1 OR id=2); 第四种四种 ->andWhere(['or like','name',['哈哈','苦苦']]); 生成的语句 WHERE `name` LIKE '%哈哈%' OR `name` LIKE '%苦苦%'; 第五种五种 addWhere(['or',['like','name','哈哈'],['like','title','苦苦']]);//操作符格式的嵌套 生成的语句 ... WHERE (`status`=1) AND ((`name` LIKE '%哈哈%') OR (`title` LIKE '%苦苦%')) |