小编给大家分享一下yii框架如何根据条件查询,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
条件查询
$customers = Customer::find()->where($cond)->all();
$cond就是我们所谓的条件,条件的写法也根据查询数据的不同存在差异,那么如何用yii2的方式来写查询条件呢?
[[简单条件]]
// SQL: (type = 1) AND (status = 2). $cond = ['type' => 1, 'status' => 2] // SQL:(id IN (1, 2, 3)) AND (status = 2) $cond = ['id' => [1, 2, 3], 'status' => 2] //SQL:status IS NULL $cond = ['status' => null]
【and】:将不同的条件组合在一起,用法举例:
//SQL:`id=1 AND id=2` $cond = ['and', 'id=1', 'id=2'] //SQL:`type=1 AND (id=1 OR id=2)` $cond = ['and', 'type=1', ['or', 'id=1', 'id=2']] //SQL:`type=1 AND (id=1 OR id=2)` //此写法'='可以换成其他操作符,例:in like != >=等 $cond = [ 'and', ['=', 'type', 1], [ 'or', ['=', 'id', '1'], ['=', 'id', '2'], ] ]
[[or]]:
/SQL:`(type IN (7, 8, 9) OR (id IN (1, 2, 3)))` $cond = ['or', ['type' => [7, 8, 9]], ['id' => [1, 2, 3]]
[[not]]:
//SQL:`NOT (attribute IS NULL)` $cond = ['not', ['attribute' => null]]
[[between]]: not between 用法相同
//SQL:`id BETWEEN 1 AND 10` $cond = ['between', 'id', 1, 10]
[[in]]: not in 用法类似
//SQL:`id IN (1, 2, 3)` $cond = ['in', 'id', [1, 2, 3]] or $cond = ['id'=>[1, 2, 3]]
//IN条件也适用于多字段 $cond = ['in', ['id', 'name'], [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]] //也适用于内嵌sql语句 $cond = ['in', 'user_id', (new Query())->select('id')->from('users')->where(['active' => 1])]
[[like]]:
//SQL:`name LIKE '%tester%'` $cond = ['like', 'name', 'tester'] //SQL:`name LIKE '%test%' AND name LIKE '%sample%'` $cond = ['like', 'name', ['test', 'sample']] //SQL:`name LIKE '%tester'` $cond = ['like', 'name', '%tester', false]
[[exists]]: not exists用法类似
//SQL:EXISTS (SELECT "id" FROM "users" WHERE "active"=1) $cond = ['exists', (new Query())->select('id')->from('users')->where(['active' => 1])]
此外,您可以指定任意运算符如下:
//SQL:`id >= 10` $cond = ['>=', 'id', 10] //SQL:`id != 10` $cond = ['!=', 'id', 10]
以上是“yii框架如何根据条件查询”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。