where方法的用法是thinkphp查询语言的精髓,也是thinkphp orm的重要组成部分和亮点所在,可以完成包括普通查询、表达式查询、快捷查询、区间查询、组合查询在内的查询操作。where方法的参数支持字符串和数组,虽然也可以使用对象但并不建议。
字符串条件$user = m(user); // 实例化user对象$user->where('type=1 and status=1')->select();
select * from think_user where type=1 and status=1
数组条件普通查询$user = m(user); // 实例化user对象$map['name'] = 'thinkphp';$map['status'] = 1; // 把查询条件传入查询方法$user->where($map)->select();
select * from think_user where `name`='thinkphp' and status=1
表达式查询$map['字段1'] = array('表达式','查询条件1');$map['字段2'] = array('表达式','查询条件2');$model->where($map)->select(); // 也支持
$map['id'] = array('eq',100);
表示的查询条件就是 id = 100
$map['id'] = array('neq',100);
表示的查询条件就是 id <> 100
$map['id'] = array('gt',100);
表示的查询条件就是 id > 100
$map['id'] = array('egt',100);
表示的查询条件就是 id >= 100
$map['id'] = array('lt',100);
表示的查询条件就是 id < 100
$map['id'] = array('elt',100);
表示的查询条件就是 id <= 100
[not] like: 同sql的like
$map['name'] = array('like','thinkphp%');
查询条件就变成 name like 'thinkphp%'
$map['a'] =array('like',array('%thinkphp%','%tp'),'or');$map['b'] =array('notlike',array('%thinkphp%','%tp'),'and');
生成的查询条件就是:(a like '%thinkphp%' or a like '%tp') and (b not like '%thinkphp%' and b not like '%tp')
[not] between :同sql的[not] between, 查询条件支持字符串或者数组,例如:
$map['id'] = array('between','1,8');
$map['id'] = array('between',array('1','8'));
[not] in: 同sql的[not] in ,查询条件支持字符串或者数组,例如:
$map['id'] = array('not in','1,5,8');
$map['id'] = array('not in',array('1','5','8'));
exp:表达式,支持更复杂的查询情况
$map['id'] = array('exp',' in (1,3,8) ');
等同于
$map['id'] = array('in','1,3,8');
组合查询$user = m("user"); // 实例化user对象$map['id'] = array('neq',1);$map['name'] = 'ok';$map['_string'] = 'status=1 and score>10';$user->where($map)->select();
最后得到的查询条件就成了:( `id` != 1 ) and ( `name` = 'ok' ) and ( status=1 and score>10 )
复合查询
$where['name'] = array('like', '%thinkphp%');$where['title'] = array('like','%thinkphp%');$where['_logic'] = 'or';$map['_complex'] = $where;$map['id'] = array('gt',1);
等同于
$where['id'] = array('gt',1);$where['_string'] = ' (name like %thinkphp%) or ( title like %thinkphp) ';
查询条件是 ( id > 1) and ( ( name like '%thinkphp%') or ( title like '%thinkphp%') )
等等这些都是常用的where查询方法。
本文转自tbhacker博客园博客,原文链接:http://www.cnblogs.com/jiqing9006/p/4994302.html,如需转载请自行联系原作者
以上就是thinkphp重点方法详解之where()方法的详细内容。