search
HomeBackend DevelopmentPHP TutorialThinkPHP CURD方法之where方法详解_PHP

ThinkPHP

ThinkPHP CURD操作的查询方法中最常用但也是最复杂的就是where方法。where方法也属于模型类的连贯操作方法之一,主要用于查询和操作条件的设置。

where方法的用法是ThinkPHP查询语言的精髓,也是ThinkPHP ORM(对象关系映射)的重要组成部分和亮点所在,可以完成包括普通查询、表达式查询、快捷查询、区间查询、组合查询在内的查询操作。where方法的参数支持字符串和数组,虽然也可以使用对象但并不建议。

1.字符串条件

使用字符串条件直接查询和操作,例如:

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

最后生成的SQL语句是

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

如果使用3.1以上版本的话,使用字符串条件的时候,建议配合预处理机制,确保更加安全,例如:

$Model->where("id=%d and username='%s' and xx='%f'",array($id,$username,$xx))->select();

或者使用:

$Model->where("id=%d and username='%s' and xx='%f'",$id,$username,$xx)->select();

如果$id变量来自用户提交或者URL地址的话,如果传入的是非数字类型,则会强制格式化为数字格式后进行查询操作。
字符串预处理格式类型支持指定数字、字符串等,具体可以参考vsprintf方法的参数说明。

2.数组条件

数组条件的where用法是ThinkPHP推荐的用法。

普通查询

最简单的数组查询方式如下:

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

最后生成的SQL语句是

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

表达式查询

上面的查询条件仅仅是一个简单的相等判断,可以使用查询表达式支持更多的SQL查询语法,查询表达式的使用格式:

$map['字段1'] = array('表达式','查询条件1');
$map['字段2'] = array('表达式','查询条件2');
$Model->where($map)->select(); // 也支持

表达式不分大小写,支持的查询表达式有下面几种,分别表示的含义是:

表达式 含义
EQ 等于(=)
NEQ 不等于()
GT 大于(>)
EGT 大于等于(>=)
LT 小于(
ELT 小于等于(
LIKE 模糊查询
[NOT] BETWEEN (不在)区间查询
[NOT] IN (不在)IN 查询
EXP 表达式查询,支持SQL语法

 

示例如下:

EQ :等于(=)

例如:

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

和下面的查询等效

$map['id'] = 100;

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

NEQ: 不等于()

例如:

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

表示的查询条件就是 id 100

GT:大于(>)

例如:

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

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

EGT:大于等于(>=)

例如:

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

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

LT:小于(

例如:

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

表示的查询条件就是 id

ELT: 小于等于(

例如:

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

表示的查询条件就是 id

[NOT] LIKE: 同sql的LIKE

例如:

$map['name'] = array('like','thinkphp%');

查询条件就变成 name like 'thinkphp%'

如果配置了DB_LIKE_FIELDS参数的话,某些字段也会自动进行模糊查询。例如设置了:

'DB_LIKE_FIELDS'=>'title|content'

的话,使用

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

查询条件就会变成 name like '%thinkphp%'
支持数组方式,例如

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

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

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

和下面的等效:

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

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

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

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

例如:

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

可以改成:

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

exp查询的条件不会被当成字符串,所以后面的查询条件可以使用任何SQL支持的语法,包括使用函数和字段名称。

查询表达式不仅可用于查询条件,也可以用于数据更新,例如:

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

快捷查询

where方法支持快捷查询方式,可以进一步简化查询条件的写法,例如:

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

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

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

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

$User = M("User"); // 实例化User对象
$map['status&title'] =array('1','thinkphp','_multi'=>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'

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

区间查询

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

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

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

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

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

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

组合查询

组合查询用于复杂的查询条件,如果你需要在查询的时候同时偶尔使用字符串却又不希望丢失数组方式的灵活的话,可以考虑使用组合查询。

组合查询的主体还是采用数组方式查询,只是加入了一些特殊的查询支持,包括字符串模式查询(_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") ';

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

3.多次调用

自3.1.3版本开始,where方法支持多次调用,但字符串条件只能出现一次,例如:

$map['a'] = array('gt',1);
$where['b'] = 1;
$Model->where($map)->where($where)->where('status=1')->select();

多次的数组条件表达式会最终合并,但字符串条件则只支持一次。

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
PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)