Where 条件表达式基础格式
Where 条件表达式的构建遵循特定格式:
$map['字段名'] = array('表达式', '操作条件');
在此结构中,$map 代表一个常规数组变量,开发者可根据实际需求自定义其名称。上述格式中所涉及的符号,实质上对应着特定的运算符含义:
| TP运算符 | SQL运算符 | 例子 | 实际查询条件 |
|---|---|---|---|
| eq | = | $map['id'] = array('eq',100); | 等效于:$map['id'] = 100; |
| neq | != | $map['id'] = array('neq',100); | id != 100 |
| gt | > | $map['id'] = array('gt',100); | id > 100 |
| egt | >= | $map['id'] = array('egt',100); | id >= 100 |
| lt | < | $map['id'] = array('lt',100); | id < 100 |
| elt | <= | $map['id'] = array('elt',100); | id <= 100 |
| like | like | $map<'username'> = array('like','Admin%'); | username like 'Admin%' |
| between | between and | $map['id'] = array('between','1,8'); | id BETWEEN 1 AND 8 |
| not between | not between and | $map['id'] = array('not between','1,8'); | id NOT BETWEEN 1 AND 8 |
| in | in | $map['id'] = array('in','1,5,8'); | id in(1,5,8) |
| not in | not in | $map['id'] = array('not in','1,5,8'); | id not in(1,5,8) |
| and(默认) | and | $map['id'] = array(array('gt',1),array('lt',10)); | (id > 1) AND (id < 10) |
| or | or | $map['id'] = array(array('gt',3),array('lt',10), 'or'); | (id > 3) OR (id < 10) |
| xor(异或) | xor | 两个输入中只有一个是true时,结果为true,否则为false,例子略。 | 1 xor 1 = 0 |
| exp | 综合表达式 | $map['id'] = array('exp','in(1,3,8)'); | $map['id'] = array('in','1,3,8'); |
补充说明
• 与 SQL 规范一致,ThinkPHP 的运算符不区分大小写,因此 eq 与 EQ 具有相同效力。
• between 和 in 条件既接受字符串也支持数组形式,这意味着以下两种写法在功能上是等效的:
$map['id'] = array('not in','1,5,8');
$map['id'] = array('not in',array('1','5','8'));
exp 表达式
前述表格中的 exp 并非传统意义上的运算符,而是一种用于实现复杂条件设置的综合性表达式。使用 exp 时,其操作内容不会被视作普通字符串,而是可以直接采用任何 SQL 支持的语法结构,包括调用数据库函数及引用字段名称。
exp 的应用范围不仅限于 where 查询条件,同样适用于数据更新操作,例如:
$Dao = M("Article");
//构建 save 的数据数组,文章点击数+1
$data['id'] = 10;
$data['counter'] = array('exp','counter+1');
//根据条件保存修改的数据
$User->save($data);
以上这篇ThinkPHP Where 条件中常用表达式示例(详解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持本站。