Home >Backend Development >PHP Tutorial >thinkphp query,3.X 5.0 method

thinkphp query,3.X 5.0 method

陈政宽~
陈政宽~Original
2017-06-28 13:12:541621browse

The following editor will bring you a thinkphp query, 3.X 5.0 method (it is feasible to try it yourself). The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor and take a look.

1. Introduction

ThinkPHP has built-in very flexible query methods that can quickly query data Operations, query conditions can be used for operations such as reading, updating, and deleting, which mainly involve 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 use expression queries There will be differences), 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 a query condition, because it will be safer.

1. Use strings as query conditions

This is the most traditional way, but it is not very safe, for example:

<?php 
$User = M("User"); // 实例化User对象 
$User->where(&#39;type=1 AND status=1&#39;)->select(); 
?>

The last generated SQL statement is

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

When using string query, we can use the string provided by the new version The safety preprocessing mechanism of conditions will not be discussed in detail for the time being.

2. Use arrays as query conditions

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

<?php 
$User = M("User"); // 实例化User对象 
$condition[&#39;name&#39;] = &#39;thinkphp&#39;; 
$condition[&#39;status&#39;] = 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 the default logical judgment can be changed using the following rules, by using _logic to define query logic:

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

The final generated SQL statement is

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

3. Use the object method to query

Here, take the stdClass built-in object as an example :

<?php 
$User = M("User"); // 实例化User对象 
// 定义查询条件 
$condition = new stdClass(); 
$condition->name = &#39;thinkphp&#39;; 
$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

Use object mode to query and use The effects of array queries are the same and are interchangeable. In most cases, we recommend using the array method to be more efficient.

3. Expression query

The above query condition is just a simple equality judgment. Query expressions can be used to support more SQL query syntax is also the essence of ThinkPHP query language.

The format of query expression: $map['field name'] = array('expression','query condition');

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

EQ is equal to (=)
NEQ is not equal to (a8093152e673feb7aba1828c43532094)
GT is greater than (>)
EGT is greater than or equal to (>=)
LT is less than (<)
ELT is less than or equal to (<=)
LIKE fuzzy query
[NOT] BETWEEN (not in) interval query
[NOT] IN (not in)IN query
EXP expression query, supports SQL syntax

The example is as follows:

1.EQ: equal to (=)

For example: $map['id'] = array('eq',100); and the following query, etc. The query condition represented by $map['id'] = 100; is id = 100

2.NEQ: Not equal to (a8093152e673feb7aba1828c43532094)

For example :$map['id'] = array('neq',100); The query condition represented is id a8093152e673feb7aba1828c43532094 100

3.GT: Greater than (>)

For example: $map['id'] = array('gt',100); The query condition represented is id > 100

4.EGT: greater than or equal to ( >=)

For example: $map['id'] = array('egt',100); The query condition represented is id >= 100

5.LT: Less than (518c659a5817a106c798d708fc22f2eb'title|content' is set, use $map['title'] = 'thinkphp'; the query condition will become name like '%thinkphp%'


Support array mode:

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

8.[NOT] BETWEEN :同sql的[not] between, 查询条件支持字符串或者数组,

例如: $map['id'] = array('between','1,8');和下面的等效: $map['id'] = array('between',array('1','8'));

查询条件就变成 id BETWEEN 1 AND 8

9.[NOT] IN: 同sql的[not] in ,查询条件支持字符串或者数组,

例如: $map['id'] = array('not in','1,5,8');和下面的等效: $map['id'] = array('not in',array('1','5','8'));

查询条件就变成 id NOT IN (1,5, 8)

10.EXP:表达式,支持更复杂的查询情况

例如:$map['id'] = array('in','1,3,8');可以改成: $map['id'] = array('exp',' IN (1,3,8) ');

exp查询的条件不会被当成字符串,所以后面的查询条件可以使用任何SQL支持的语法,包括使用函数和字段名称。查询表达式不仅可用于查询条件,也可以用于数据更新,例如:

<?php 
$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); // 根据条件保存修改的数据 
?>

四、快捷查询

从3.0版本开始,增加了快捷查询方式,可以进一步简化查询条件的写法,例如:

1.实现不同字段相同的查询条件

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

查询条件就变成

name= 'thinkphp' OR title = 'thinkphp'

2.实现不同字段不同的查询条件

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

'_multi'=>true必须加在数组的最后,表示当前是多条件匹配,这样查询条件就变成 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'

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

五、区间查询

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

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

得到的查询条件是: (`id` > 1) AND (`id` 13e6bb2942fd9623f93f45b2b42d7d12 3) OR (`id` 3a5daf68982d23e74067037833b54044 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')

六、组合查询

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

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

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

<?php 
$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(); 
?>

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

( `id` != 1 ) AND ( `name` = 'ok' ) AND ( status=1 AND score>10 )

2.请求字符串查询方式

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

<?php 
$map[&#39;id&#39;] = array(&#39;gt&#39;,&#39;100&#39;); 
$map[&#39;_query&#39;] = &#39;status=1&score=100&_logic=or&#39;; 
?>

得到的查询条件是:

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

七、复合查询

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

例如:

<?php 
$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); 
?>

查询条件是

( 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") ';

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

八、统计查询

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

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

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

九、SQL查询

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

1.query方法 :执行SQL查询操作

用法 query($sql,$parse=false)

参数 sql(必须):要查询的SQL语句

parse(可选):是否需要解析SQL

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

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

使用示例

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

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

2.execute方法 :execute用于更新和写入数据的sql操作

用法 execute($sql,$parse=false)

参数 sql(必须):要执行的SQL语句

parse(可选):是否需要解析SQL

返回值 如果数据非法或者查询错误则返回false 否则返回影响的记录数

使用示例:

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

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

十、动态查询

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

getBy 根据字段的值查询数据 例如,getByName,getByEmail
getFieldBy 根据字段查询并返回某个字段的值 例如,getFieldByName

1.getBy动态查询:该查询方式针对数据表的字段进行查询记录

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

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

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

2.getFieldBy dynamic query: query a certain field and return the value of a certain field, for example

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

means to obtain the user's id value based on the user's name.

11. Subquery

Since version 3.0, subquery support has been added, and there are two ways to use it:

1. Use the select method

When the parameter of the select method is false, it means that no query is performed and only the constructed SQL is returned, for example:

// Construct first Subquery SQL
$subQuery = $model->field('id,name')->table('tablename')->group('field')->where($where)-> ;order('status')->select(false);

When the select method passes in the false parameter, it means that the current query will not be executed, but only the query SQL will be generated.

2. Use the buildSql method

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

The actual query operation will not be performed after calling the buildSql method, but It only generates the SQL statement for this query (in order to avoid confusion, parentheses will be added on both sides of the SQL), and then we call it directly in subsequent queries.

//Use subquery to query
$model->table($subQuery.' a')->where()->order()->select()

The constructed subquery SQL can be used in ThinkPHP's coherent operation methods, such as table where, etc.

The above thinkphp query, 3. Home.

The above is the detailed content of thinkphp query,3.X 5.0 method. For more information, please follow other related articles on the PHP Chinese website!

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