Home > Backend Development > PHP Tutorial > Detailed explanation of the usage of $map in ThinkPHP

Detailed explanation of the usage of $map in ThinkPHP

*文
Release: 2023-03-19 07:00:01
Original
4490 people have browsed it

ThinkPHP has built-in very flexible query methods, which can quickly perform data query operations. The query conditions can be used for any operation such as CURD, and can be passed in as parameters of the where method. Let’s explain the connotation of the query language one by one.


Query method

ThinkPHP can support the direct use of strings as query conditions, but in most cases It is recommended to use index arrays or objects as query conditions because it is safer.
1. Use strings as query conditions
This is the most traditional way, but it is not very safe. For example:

$User = M("User"); // 实例化User对象
$User->where('type=1 AND status=1')->select();
Copy after login

Finally generated The SQL statement is

SELECT * FROM think_user WHERE type=1 AND status=1
Copy after login


2. Use arrays as query conditions

$User = M("User"); // 实例化User对象
$condition['name'] = 'thinkphp';
$condition['status'] = 1;
 // 把查询条件传入查询方法
$User->where($condition)->select(); 
最后生成的SQL语句是SELECT * FROM think_user WHERE `name`='thinkphp' AND status=1如果进行多字段查询,那么字段之间的默认逻辑关系是 逻辑与 AND,但是用下面的规则可以更改默认的逻辑判断,通过使用 _logic 定义查询逻辑:
$User = M("User"); // 实例化User对象
$condition['name'] = 'thinkphp';
$condition['account'] = 'thinkphp';
$condition['_logic'] = 'OR';
 // 把查询条件传入查询方法
$User->where($condition)->select();
Copy after login

The last generated SQL statement is

SELECT * FROM think_user WHERE `name`='thinkphp' OR `account`='thinkphp'
Copy after login

3. Use the object method to query (here, take the stdClass built-in object as an example)

$User = M("User"); // 实例化User对象
 // 定义查询条件
$condition = new stdClass(); 
$condition->name = 'thinkphp'; 
$condition->status= 1; 
$User->where($condition)->select();
Copy after login

The final generated SQL statement is the same as above
SELECT * FROM think_user WHERE `name`='thinkphp' AND status=1
The effect of using object mode query and using array query is the same. And they are interchangeable. In most cases, we recommend using the array method to be more efficient. Later we will use the array method as an example to explain the specific query language usage.

Expression query

The above query condition is just a simple equality judgment. Query expressions can be used to support more SQL query syntax, and can be used for array or object queries. (The following only uses array mode as an example). The usage format of query expressions:
$map['field name'] = array('expression','query condition');
Expressions are not separated. Upper and lower case, the following query expressions are supported, and their respective meanings are:

ExpressionMeaning
EQEqual to (=)
NEQNot equal to (<>)
GTGreater than (>)
EGTGreater than or equal to (>=)
LTLess than (<)
ELTLess than or equal to (<=)
LIKEFuzzy query
[NOT] BETWEEN(Not)Interval query
[NOT] IN(Not) IN query
EXPExpression query, supports SQL syntax

Examples are as follows:
EQ: equal to (=)
For example:

$map['id'] = array ('eq',100);

is equivalent to the following query

$map['id'] = 100;## The query condition represented by

# 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 by

is id > 100



EGT: greater than or equal to (>=) For example:

$map['id'] = array('egt',100);

represents the query condition id >= 100



LT:Less than (<)For example:

##$map['id'] = array('lt',100) The query condition represented by ;

is id < 100


ELT
: less than or equal to (<=)For example:

$map['id'] = array('elt',100);The query condition represented by

is id <= 100


[NOT] LIKE
: Same as sql 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 query. For example, if you set:


'DB_LIKE_FIELDS'=>'title|content'

, use

$map['title'] = 'thinkphp';

The query condition will become name like '%thinkphp%'

Supports array mode, for example


$map['a'] =array('like',array('%thinkphp%','%tp'),'OR');

$map['b'] =array('notlike',array('%thinkphp%','%tp'),'AND');

The generated query conditions are:

(a like '%thinkphp%' OR a like '%tp') AND (b not like '%thinkphp%' AND b not like '%tp')



[NOT] BETWEEN
: Same as sql's [not] between, query conditions support strings or arrays, for example:

$map['id '] = array('between','1,8');

is equivalent to the following:

$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');

is equivalent to the following:

$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 situationsFor example:

$map['id'] = array( 'in','1,3,8');

can be changed to:

<p><span style="margin:0px;padding:0px;">$map[&#39;id&#39;] = array(&#39;exp&#39;,&#39; IN (1,3,8) &#39;);</span></p><p>exp查询的条件不会被当成字符串,所以后面的查询条件可以使用任何SQL支持的语法,包括使用函数和字段名称。查询表达式不仅可用于查询条件,也可以用于数据更新,例如:<code style="margin:0px;padding:0px;">

$User = M("User"); // 实例化User对象
 // 要修改的数据对象属性赋值
$data[&#39;name&#39;] = &#39;ThinkPHP&#39;;
$data[&#39;score&#39;] = array(&#39;exp&#39;,&#39;score+1&#39;);// 用户的积分加1
$User->where(&#39;id=5&#39;)->save($data); // 根据条件保存修改的数据
Copy after login

快捷查询

新版增加了快捷查询方式,可以进一步简化查询条件的写法,例如:
一、实现不同字段相同的查询条件

$User = M("User"); // 实例化User对象
$map[&#39;name|title&#39;] = &#39;thinkphp&#39;;
 // 把查询条件传入查询方法
$User->where($map)->select();
Copy after login

查询条件就变成 name= 'thinkphp' OR title = 'thinkphp'

二、实现不同字段不同的查询条件

$User = M("User"); // 实例化User对象
$map[&#39;status&title&#39;] =array(&#39;1&#39;,&#39;thinkphp&#39;,&#39;_multi&#39;=>true);
 // 把查询条件传入查询方法
$User->where($map)->select();
Copy after login

'_multi'=>true必须加在数组的最后,表示当前是多条件匹配,这样查询条件就变成 status= 1 AND title = 'thinkphp' ,查询字段支持更多的,例如:

$map[&#39;status&score&title&#39;] =array(&#39;1&#39;,array(&#39;gt&#39;,&#39;0&#39;),&#39;thinkphp&#39;,&#39;_multi&#39;=>true);
Copy after login

查询条件就变成 status= 1 AND score >0 AND title = 'thinkphp'

注意:快捷查询方式中“|”和“&”不能同时使用。

区间查询

ThinkPHP支持对某个字段的区间查询,例如:

$map[&#39;id&#39;] = array(array(&#39;gt&#39;,1),array(&#39;lt&#39;,10)) ;
Copy after login

得到的查询条件是: (`id` > 1) AND (`id` < 10)

$map[&#39;id&#39;] = array(array(&#39;gt&#39;,3),array(&#39;lt&#39;,10), &#39;or&#39;) ;
Copy after login

得到的查询条件是: (`id` > 3) OR (`id` < 10)

$map[&#39;id&#39;]  = array(array(&#39;neq&#39;,6),array(&#39;gt&#39;,3),&#39;and&#39;);
Copy after login

得到的查询条件是:(`id` != 6) AND (`id` > 3)
最后一个可以是AND、 OR或者 XOR运算符,如果不写,默认是AND运算。
区间查询的条件可以支持普通查询的所有表达式,也就是说类似LIKE、GT和EXP这样的表达式都可以支持。另外区间查询还可以支持更多的条件,只要是针对一个字段的条件都可以写到一起,例如:

$map[&#39;name&#39;]  = array(array(&#39;like&#39;,&#39;%a%&#39;), array(&#39;like&#39;,&#39;%b%&#39;), array(&#39;like&#39;,&#39;%c%&#39;), &#39;ThinkPHP&#39;,&#39;or&#39;);
Copy after login

最后的查询条件是:

(`name` LIKE &#39;%a%&#39;) OR (`name` LIKE &#39;%b%&#39;) OR (`name` LIKE &#39;%c%&#39;) OR (`name` = &#39;ThinkPHP&#39;)
Copy after login


组合查询

如果你需要在查询的时候同时偶尔使用字符串却又不希望丢失数组方式的灵活的话,可以考虑使用组合查询。
组合查询的主体还是采用数组方式查询,只是加入了一些特殊的查询支持,包括字符串模式查询(_string)、复合查询(_complex)、请求字符串查询(_query),混合查询中的特殊查询每次查询只能定义一个,由于采用数组的索引方式,索引相同的特殊查询会被覆盖。
一、字符串模式查询(采用_string 作为查询条件)
数组条件还可以和字符串条件混合使用,例如:

$User = M("User"); // 实例化User对象
$map[&#39;id&#39;] = array(&#39;neq&#39;,1);
$map[&#39;name&#39;] = &#39;ok&#39;;
$map[&#39;_string&#39;] = &#39;status=1 AND score>10&#39;;
$User->where($map)->select();
Copy after login

最后得到的查询条件就成了:

( `id` != 1 ) AND ( `name` = &#39;ok&#39; ) AND ( status=1 AND score>10 )
Copy after login


二、请求字符串查询方式
请求字符串查询是一种类似于URL传参的方式,可以支持简单的条件相等判断。

$map[&#39;id&#39;] = array(&#39;gt&#39;,&#39;100&#39;);
$map[&#39;_query&#39;] = &#39;status=1&score=100&_logic=or&#39;;
Copy after login

得到的查询条件是:`id`>100 AND (`status` = '1' OR `score` = '100')

三、复合查询
复合查询相当于封装了一个新的查询条件,然后并入原来的查询条件之中,所以可以完成比较复杂的查询条件组装。
例如:

$where[&#39;name&#39;]  = array(&#39;like&#39;, &#39;%thinkphp%&#39;);
$where[&#39;title&#39;]  = array(&#39;like&#39;,&#39;%thinkphp%&#39;);
$where[&#39;_logic&#39;] = &#39;or&#39;;
$map[&#39;_complex&#39;] = $where;
$map[&#39;id&#39;]  = array(&#39;gt&#39;,1);
Copy after login

查询条件是
( id > 1) AND ( ( name like '%thinkphp%') OR ( title like '%thinkphp%') )
复合查询使用了_complex作为子查询条件来定义,配合之前的查询方式,可以非常灵活的制定更加复杂的查询条件。
很多查询方式可以相互转换,例如上面的查询条件可以改成:

$where[&#39;id&#39;] = array(&#39;gt&#39;,1);
$where[&#39;_string&#39;] = &#39; (name like "%thinkphp%")  OR ( title like "%thinkphp") &#39;;
Copy after login

最后生成的SQL语句是一致的。

统计查询

在应用中我们经常会用到一些统计数据,例如当前所有(或者满足某些条件)的用户数、所有用户的最大积分、用户的平均成绩等等,ThinkPHP为这些统计操作提供了一系列的内置方法,包括:

方法说明
Count统计数量,参数是要统计的字段名(可选)
Max获取最大值,参数是要统计的字段名(必须)
Min获取最小值,参数是要统计的字段名(必须)
Avg获取平均值,参数是要统计的字段名(必须)
Sum获取总分,参数是要统计的字段名(必须)

用法示例:

$User = M("User"); // 实例化User对象
Copy after login

获取用户数:

$userCount = $User->count();
Copy after login

或者根据字段统计:

$userCount = $User->count("id");
Copy after login

获取用户的最大积分:

$maxScore = $User->max(&#39;score&#39;);
Copy after login

获取积分大于0的用户的最小积分:

$minScore = $User->where(&#39;score>0&#39;)->min(&#39;score&#39;);
Copy after login

获取用户的平均积分:

$avgScore = $User->avg(&#39;score&#39;);
Copy after login

统计用户的总成绩:

$sumScore = $User->sum(&#39;score&#39;);
Copy after login

并且所有的统计查询均支持连贯操作的使用。


定位查询

ThinkPHP支持定位查询,但是要求当前模型必须继承高级模型类才能使用,可以使用getN方法直接返回查询结果中的某个位置的记录。例如:
获取符合条件的第3条记录:

$User->where(&#39;score>0&#39;)->order(&#39;score desc&#39;)->getN(2);
Copy after login

获取符合条件的最后第二条记录:

$User-> where(&#39;score>80&#39;)->order(&#39;score desc&#39;)->getN(-2);
Copy after login

获取第一条记录:

$User->where(&#39;score>80&#39;)->order(&#39;score desc&#39;)->first();
Copy after login

获取最后一条记录:

$User->where(&#39;score>80&#39;)->order(&#39;score desc&#39;)->last();
Copy after login

SQL查询

ThinkPHP内置的ORM和ActiveRecord模式实现了方便的数据存取操作,而且新版增加的连贯操作功能更是让这个数据操作更加清晰,但是ThinkPHP仍然保留了原生的SQL查询和执行操作支持,为了满足复杂查询的需要和一些特殊的数据操作,SQL查询的返回值因为是直接返回的Db类的查询结果,没有做任何的处理。主要包括下面两个方法:
1、query方法

query 执行SQL查询操作
用法query($sql,$parse=false)
参数query(必须):要查询的SQL语句
parse(可选):是否需要解析SQL
返回值

如果数据非法或者查询错误则返回false


否则返回查询结果数据集(同select方法)

使用示例:

$Model = new Model() // 实例化一个model对象 没有对应任何数据表
$Model->query("select * from think_user where status=1");
Copy after login

如果你当前采用了分布式数据库,并且设置了读写分离的话,query方法始终是在读服务器执行,因此query方法对应的都是读操作,而不管你的SQL语句是什么。

2、execute方法

execute用于更新和写入数据的sql操作
用法execute($sql,$parse=false)
参数query(必须):要执行的SQL语句
parse(可选):是否需要解析SQL
返回值如果数据非法或者查询错误则返回false
否则返回影响的记录数

使用示例:

$Model = new Model() // 实例化一个model对象 没有对应任何数据表
$Model->execute("update think_user set name=&#39;thinkPHP&#39; where status=1");
Copy after login

如果你当前采用了分布式数据库,并且设置了读写分离的话,execute方法始终是在写服务器执行,因此execute方法对应的都是写操作,而不管你的SQL语句是什么。

3、其他技巧
自动获取当前表名
通常使用原生SQL需要手动加上当前要查询的表名,如果你的表名以后会变化的话,那么就需要修改每个原生SQL查询的sql语句了,针对这个情况,系统还提供了一个小的技巧来帮助解决这个问题。
例如:

$model = M("User");
$model->query(&#39;select * from __TABLE__ where status>1&#39;);
Copy after login

我们这里使用了__TABLE__ 这样一个字符串,系统在解析的时候会自动替换成当前模型对应的表名,这样就可以做到即使模型对应的表名有所变化,仍然不用修改原生的sql语句。

支持连贯操作和SQL解析
新版对query和execute两个原生SQL操作方法增加第二个参数支持, 表示是否需要解析SQL (默认为false 表示直接执行sql ),如果设为true 则会解析SQL中的特殊字符串 (需要配合连贯操作)。
例如,支持 如下写法:

$model->table("think_user")
      ->where(array("name"=>"thinkphp"))
      ->field("id,name,email")
      ->query(&#39;select %FIELD% from %TABLE% %WHERE%&#39;,true);
Copy after login

其中query方法中的%FIELD%、%TABLE%和%WHERE%字符串会自动替换为同名的连贯操作方法的解析结果SQL,支持的替换字符串包括:

替换字符串对应连贯操作方法
%FIELD%field
%TABLE%table
%DISTINCT%distinct
%WHERE%where
%JOIN%join
%GROUP%group
%HAVING%having
%ORDER%order
%LIMIT%limit
%UNION%union

Dynamic Query

With the help of the characteristics of PHP5 language, ThinkPHP implements dynamic query, including the following types:

Method nameExplanationExample
getByQuery data based on the value of a certain fieldFor example, getByName, getByEmail
getFieldByQuery and return the value of a certain field based on a certain fieldFor example, getFieldByName
topGet the first number of records (requires advanced model support)For example, top8, top12


一、getBy动态查询

该查询方式针对数据表的字段进行查询。例如,User对象拥有id,name,email,address 等属性,那么我们就可以使用下面的查询方法来直接根据某个属性来查询符合条件的记录。

$user = $User->getByName(&#39;liu21st&#39;);
$user = $User->getByEmail(&#39;liu21st@gmail.com&#39;);
$user = $User->getByAddress(&#39;中国深圳&#39;);
Copy after login

暂时不支持多数据字段的动态查询方法,请使用find方法和select方法进行查询。

二、getFieldBy动态查询
针对某个字段查询并返回某个字段的值,例如

$user = $User->getFieldByName(&#39;liu21st&#39;,&#39;id&#39;);
Copy after login

表示根据用户的name获取用户的id值。

三、top动态查询
ThinkPHP还提供了另外一种动态查询方式,就是获取符合条件的前N条记录(和定位查询一样,也要求当前模型类必须继承高级模型类后才能使用)。例如,我们需要获取当前用户中积分大于0,积分最高的前5位用户 :

$User-> where(&#39;score>80&#39;)->order(&#39;score desc&#39;)->top5();
Copy after login

要获取积分的前8位可以改成:

$User-> where(&#39;score>80&#39;)->order(&#39;score desc&#39;)->top8();
Copy after login

子查询

新版新增了子查询支持,有两种使用方式:
1、使用select方法
当select方法的参数为false的时候,表示不进行查询只是返回构建SQL,例如:

// 首先构造子查询SQL 
$subQuery = $model->field(&#39;id,name&#39;)->table(&#39;tablename&#39;)->group(&#39;field&#39;)->where($where)->order(&#39;status&#39;)->select(false);
Copy after login

2、使用buildSql方法

$subQuery = $model->field(&#39;id,name&#39;)->table(&#39;tablename&#39;)->group(&#39;field&#39;)->where($where)->order(&#39;status&#39;)->buildSql();
Copy after login

调用buildSql方法后不会进行实际的查询操作,而只是生成该次查询的SQL语句(为了避免混淆,会在SQL两边加上括号),然后我们直接在后续的查询中直接调用。

// 利用子查询进行查询 
$model->table($subQuery.&#39; a&#39;)->where()->order()->select()
Copy after login

构造的子查询SQL可用于TP的连贯操作方法,例如table where等。

相关推荐:

详解ThinkPHP如何实现生成和校验验证码

thinkphp5上传图片及生成缩略图方法

详解ThinkPHP的行为扩展和插件

The above is the detailed content of Detailed explanation of the usage of $map in ThinkPHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template