条件查询
$customers = Customer::find()->where($cond)->all();
$cond就是我们所谓的条件,条件的写法也根据查询数据的不同存在差异,那么如何用yii2的方式来写查询条件呢?
[[简单条件]]
-
- $cond = ['type' => 1, 'status' => 2]
-
-
- $cond = ['id' => [1, 2, 3], 'status' => 2]
-
-
- $cond = ['status' => null]
[【and】]:将不同的条件组合在一起,用法举例:
-
- $cond = ['and', 'id=1', 'id=2']
-
-
- $cond = ['and', 'type=1', ['or', 'id=1', 'id=2']]
-
-
- $cond = [
- 'and',
- ['=', 'type', 1],
- [
- 'or',
- ['=', 'id', '1'],
- ['=', 'id', '2'],
- ]
- ]
[[or]]:
-
- $cond = ['or', ['type' => [7, 8, 9]], ['id' => [1, 2, 3]]
[[not]]:
-
- $cond = ['not', ['attribute' => null]]
[[between]]: not between 用法相同
-
- $cond = ['between', 'id', 1, 10]
[[in]]: not in 用法类似
-
- $cond = ['in', 'id', [1, 2, 3]] or $cond = ['id'=>[1, 2, 3]]
-
-
- $cond = ['in', ['id', 'name'], [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]]
-
-
- $cond = ['in', 'user_id', (new Query())->select('id')->from('users')->where(['active' => 1])]
[[like]]:
-
- $cond = ['like', 'name', 'tester']
-
-
- $cond = ['like', 'name', ['test', 'sample']]
-
-
- $cond = ['like', 'name', '%tester', false]
[[exists]]: not exists用法类似
-
- $cond = ['exists', (new Query())->select('id')->from('users')->where(['active' => 1])]
此外,您可以指定任意运算符如下
-
- $cond = ['>=', 'id', 10]
-
-
- $cond = ['!=', 'id', 10]