Home >Backend Development >PHP Tutorial >ThinkPHP3.1 query language detailed explanation_PHP tutorial

ThinkPHP3.1 query language detailed explanation_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:24:29914browse

ThinkPHP’s query language combined with coherent operations can well solve complex business logic requirements. In this article, we will first have an in-depth understanding of the query language of the framework.

1. Query language introduction

ThinkPHP has built-in very flexible query methods, which can quickly perform data query operations. Query conditions can be used for operations such as reading, updating, and deleting. It mainly involves coherent operations such as the where method, no matter what database is used. , you almost use the same query method (some databases such as Mongo will have different expression queries), and the system helps you solve the differences between different databases, so we call this query method of the framework a query language. The query language is also the ORM highlight of the ThinkPHP framework, making query operations simpler and easier to understand. Let’s explain the connotation of query language one by one.

2. 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 method, but it is not very safe, for example:

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

The final generated SQL statement is

SELECT * FROM think_user WHERE type=1 AND status=1

When using string queries, we can use the security preprocessing mechanism for string conditions provided by the new version, which we will not go into details for now.

2. Use array as query condition

This method is the most commonly used query method, for example:

$User = M("User"); // 实例化User对象
$condition['name'] = 'thinkphp';
$condition['status'] = 1;
 // 把查询条件传入查询方法
$User->where($condition)->select(); 

The final generated SQL statement is

SELECT * FROM think_user WHERE `name`='thinkphp' AND status=1

If you perform a multi-field query, the default logical relationship between fields is logical AND, but you can change the default logical judgment using the following rules, by using _logic to define the query logic:

$User = M("User"); // 实例化User对象
$condition['name'] = 'thinkphp';
$condition['account'] = 'thinkphp';
$condition['_logic'] = 'OR';
 // 把查询条件传入查询方法
$User->where($condition)->select(); 

The final generated SQL statement is

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

3. Use object method to query

Here is 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(); 

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 mode query is the same and can be interchanged. In most cases, we recommend using array mode to be more efficient.

3. Expression query

The above query condition is just a simple equality judgment. You can use query expressions to support more SQL query syntax, which is also the essence of ThinkPHP query language. The usage format of query expressions:

$map['字段名'] = array('表达式','查询条件');

Expressions are not case-sensitive. The supported query expressions are as follows, and their respective meanings are:


Expression Meaning
EQ Equal (=)
NEQ Not equal to (a8093152e673feb7aba1828c43532094)
GT Greater than (>)
EGT Greater than or equal to (>=)
LT Less than (<)
ELT Less than or equal to (<=)
LIKE Fuzzy query
[NOT] BETWEEN (not) interval query
[NOT] IN (not in)IN query
EXP Expression query, supports SQL syntax

示例如下:

EQ :等于(=)

例如:

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

和下面的查询等效

$map['id'] = 100;

表示的查询条件就是 id = 100

NEQ: 不等于(a8093152e673feb7aba1828c43532094)

例如:

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

表示的查询条件就是 id a8093152e673feb7aba1828c43532094 100

GT:大于(>)

例如:

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

表示的查询条件就是 id > 100

EGT:大于等于(>=)

例如:

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

表示的查询条件就是 id >= 100

LT:小于(cdb8ed392b7144e7380d0df64b0b773ftrue必须加在数组的最后,表示当前是多条件匹配,这样查询条件就变成

status= 1 AND title = 'thinkphp'

查询字段支持更多的,例如:

$map['status&score&title'] =array('1',array('gt','0'),'thinkphp','_multi'=>true);

查询条件就变成

status= 1 AND score >0 AND title = 'thinkphp'

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

5.区间查询

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

$map['id'] = array(array('gt',1),array('lt',10)) ;

得到的查询条件是:

(`id` > 1) AND (`id` < 10)

$map['id'] = array(array('gt',3),array('lt',10), 'or') ;

得到的查询条件是:

(`id` > 3) OR (`id` < 10)
$map['id'] = array(array('neq',6),array('gt',3),'and'); 

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

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


6.组合查询

组合查询的主体还是采用数组方式查询,只是加入了一些特殊的查询支持,包括字符串模式查询(_string)、复合查询(_complex)、请求字符串查询(_query),混合查询中的特殊查询每次查询只能定义一个,由于采用数组的索引方式,索引相同的特殊查询会被覆盖。

一、字符串模式查询(采用_string 作为查询条件)

数组条件还可以和字符串条件混合使用,例如:

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

二、请求字符串查询方式

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

$map['id'] = array('gt','100');
$map['_query'] = 'status=1&score=100&_logic=or';

得到的查询条件是:

`id`>100 AND (`status` = '1' OR `score` = '100')

三、复合查询

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

$where['name'] = array('like', '%thinkphp%');
$where['title'] = array('like','%thinkphp%');
$where['_logic'] = 'or';
$map['_complex'] = $where;
$map['id'] = array('gt',1);

查询条件是

( id > 1) AND ( ( name like '%thinkphp%') OR ( title like '%thinkphp%') )

复合查询使用了_complex作为子查询条件来定义,配合之前的查询方式,可以非常灵活的制定更加复杂的查询条件。
很多查询方式可以相互转换,例如上面的查询条件可以改成:

$where['id'] = array('gt',1);
$where['_string'] = ' (name like "%thinkphp%") OR ( title like "%thinkphp") ';

The final generated SQL statement is consistent.

7. Statistical query

In applications, we often use some statistical data, such as the current number of users (or those who meet certain conditions), the maximum points of all users, the average score of users, etc. ThinkPHP provides a method for these statistical operations. A series of built-in methods, including:

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

 

用法示例:

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

获取用户数:

$userCount = $User->count();

或者根据字段统计:

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

获取用户的最大积分:

$maxScore = $User->max('score');

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

$minScore = $User->where('score>0')->min('score');

获取用户的平均积分:

$avgScore = $User->avg('score');

统计用户的总成绩:

$sumScore = $User->sum('score');

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

8.SQL查询

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

一、query方法

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

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


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

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

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

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

使用示例:
$Model = new Model() // 实例化一个model对象 没有对应任何数据表
$Model->execute("update think_user set name='thinkPHP' where status=1");

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

9.动态查询

借助PHP5语言的特性,ThinkPHP实现了动态查询,核心模型的动态查询方法包括下面几种:


方法名 说明 举例
getBy 根据字段的值查询数据 例如,getByName,getByEmail
getFieldBy 根据字段查询并返回某个字段的值 例如,getFieldByName
一、getBy动态查询

该查询方式针对数据表的字段进行查询。例如,User对象拥有id,name,email,address 等属性,那么我们就可以使用下面的查询方法来直接根据某个属性来查询符合条件的记录。
$user = $User->getByName('liu21st');
$user = $User->getByEmail('liu21st@gmail.com');
$user = $User->getByAddress('中国深圳');

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

二、getFieldBy动态查询

针对某个字段查询并返回某个字段的值,例如

$userId = $User->getFieldByName('liu21st','id');

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

10.子查询

从3.0版本开始新增了子查询支持,有两种使用方式:

1、使用select方法

当select方法的参数为false的时候,表示不进行查询只是返回构建SQL,例如:

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

当select方法传入false参数的时候,表示不执行当前查询,而只是生成查询SQL。

2、使用buildSql方法

$subQuery = $model->field('id,name')->table('tablename')->group('field')->where($where)->order('status')->buildSql(); 

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

// 利用子查询进行查询 
$model->table($subQuery.' a')->where()->order()->select() 

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

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/825431.htmlTechArticleThinkPHP的查询语言配合连贯操作可以很好解决复杂的业务逻辑需求,本篇我们就首先来深入了解下框架的查询语言。 1.查询语言介绍 ThinkP...
Statement:
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