Home >Backend Development >PHP Tutorial >thinkphp model filter query field, expression method_PHP tutorial
Use query expressions
Query expression usage format:
$map['field name'] = array('expression', 'query condition');
Expressions are not case-sensitive. The supported query expressions are as follows, and their respective meanings are:
EQ: equal to (=)
For example: $map['id'] = array('eq',100);
Equivalent to the following query
$map['id'] = 100;
The query condition represented is id = 100
NEQ: Not equal to (!=)
For example: $map['id'] = array('neq',100);
The query condition represented is id != 100
GT: Greater than (>)
For example: $map['id'] = array('gt',100);
The query condition represented is id > 100
EGT: Greater than or equal to (>=)
For example: $map['id'] = array('egt',100);
The query condition represented is id >= 100
LT: less than (<)
For example: $map['id'] = array('lt',100);
The query condition represented is id < 100
ELT: Less than or equal to (<=)
For example: $map['id'] = array('elt',100);
The query condition represented is id <= 100
LIKE: Same as sql’s LIKE
For example: $map['name'] = array('like','thinkphp%');
The query condition becomes name like 'thinkphp%'
If the DB_LIKE_FIELDS parameter is configured, some fields will also automatically perform fuzzy queries. For example, set:
'DB_LIKE_FIELDS'=>'title|content'
If so, use
$map['title'] = 'thinkphp';
The query condition will become name like '%thinkphp%'
[NOT] BETWEEN: Same as SQL's [not] between, query conditions support strings or arrays, for example:
$map['id'] = array('between','1,8');
Equivalent to:
$map['id'] = array('between',array('1','8'));
The query condition becomes id BETWEEN 1 AND 8
[NOT] IN: Same as SQL's [not] in, query conditions support strings or arrays, for example:
$map['id'] = array('not in','1,5,8');
Equivalent to:
$map['id'] = array('not in',array('1','5','8'));
The query condition becomes id NOT IN (1,5, 8)
EXP: Expression, supports more complex query situations
For example:
$map['id'] = array('in','1,3,8');
Can be changed to:
$map['id'] = array('exp',' IN (1,3,8) ');
The conditions of exp query will not be treated as strings, so subsequent query conditions can use any syntax supported by SQL, including using functions and field names. Query expressions can not only be used for query conditions, but also for data updates, for example:
$User = M("User"); // Instantiate User object
//Assign the data object attributes to be modified
$data['name'] = 'ThinkPHP';
$data['score'] = array('exp','score+1'); // Add 1 to the user's points
$User->where('id=5')->save($data); // Save modified data according to conditions
The above filtering query conditions can be written in the _filter() function, such as:
//Filter query field
Function _filter(&$map){
$map['title'] = array('like',"%".$_POST['til']."%");
$map['categoryId'] = array('eq',$_REQUEST['cid']);
}