ThinkPHP之查询语言
ThinkPHP中的查询语言:
普遍查询
1)字符串形式
$list=$user->where('username=bbbb')->select();
2)数组形式
- $data['username']='bbbbb';
- $list=$user->where($data)->select();
3)对象形式
- $user=M('user');
- $a=new stdClass();
- $a->username='bbbbb';
- $list=$user->where($a)->select();
查询表达式
EQ (=)
NEQ(!=)
GT (>) LT(<) [NOT]BETWEEN(对应sql中的between) IN
EGT(>=)ELT(<=)LIKE (对应sql中的like)
EXP(使用标准sql语句实现较复杂的情况)
区间查询
- $map['id'] = array(array('gt',3),array('lt',10), 'or') ;
- $map['name'] = array(array('like','%a%'), array('like','%b%'), array('like','%c%'), 'ThinkPHP','or');
对应的查询条件是:(`name` LIKE '%a%') OR (`name` LIKE '%b%') OR (`name` LIKE '%c%') OR (`name` = 'ThinkPHP');
组合查询:
1)字符串模式查询(_string)
- $user=M('User');
- $data[id]=array('neq',1);
- $data['username']='aaaaa';
- $data['_string']='userpass=123 and createtime=2012';
- $list=$user->where($data)->select();
2)请求字符串查询方式
- $data['id']=array('gt',100);
- $data['_query']='userpass=1&username=aa&_logic=or';
- $list=$user->where($data)->select();
3)复合查询
- $wh['username']=array('like','%thinkphp%');
- $wh['userpass']=array('like','3%');
- $wh['_logic']='or';
- $data['_complex']=$wh;
- $data['id']=array('gt',100);
- $list=$user->where($data)->select();
对应于:(id>100)AND( (namelike'%thinkphp%')OR(titlelike'%thinkphp%') )
统计查询
- count():$num=$user->count();$num=$user->count('id');
- max():
- min():
- avg():
- sum():
定位查询
要求当前模型必须继承高级模型类才能使用
- $User->where('score>0')->order('score desc')->getN(2);
- $User-> where('score>80')->order('score desc')->getN(-2);
- $User->where('score>80')->order('score desc')->first();
- $User->where('score>80')->order('score desc')->last();
SQL查询
- $model=new Model();
- $list=$model->query("select * from think_user where id>1 and id<10");
- $model=new Model();
- $Model->execute("update think_user set name='thinkPHP' where status=1");
动态查询
- $user = $User->getByName('liu21st');
- $user = $User->getFieldByName('liu21st','id');
- $user-> where('score>80')->order('score desc')->top5();