ThinkPHP查询构造器通过where()方法实现安全直观的链式条件查询。支持等值查询、数组多条件、多次where调用及闭包嵌套逻辑,并提供>、>=等运算符避免SQL拼接。

ThinkPHP 的查询构造器(Query Builder)提供了链式调用方式,让条件查询更直观、安全且可读性强。核心是通过 where() 方法添加条件,配合各种运算符和逻辑组合实现灵活查询。
基础单条件查询
最常用的是等值查询,直接传字段名和值即可:
-
Db::table('user')->where('status', 1)->select();→ 查询 status = 1 的所有用户 -
Db::name('user')->where('id', 10)->find();→ 查询 id 为 10 的单条记录(name()自动补全表前缀)
多条件与复合条件
支持数组、闭包、多个 where() 链式调用三种写法:
- 数组方式(AND 关系):
where(['status' => 1, 'is_delete' => 0]) - 多次
where():->where('status', 1)->where('score', '>', 80) - 闭包方式(适合 OR 或嵌套逻辑):
->where(function ($query) {<br> $query->where('type', 1)->whereOr('type', 2);<br>})
常用查询运算符
第二个参数支持多种比较操作,避免手拼 SQL:
立即学习“PHP免费学习笔记(深入)”;
'>'、'>='、''(不等于)、'like'、'in'、'not in'、'between'、'not between'- 例如:
->where('age', 'between', [18, 60])
->where('username', 'like', '%admin%')
->where('id', 'in', [1,2,3])
动态条件与空值处理
实际开发中常需根据参数动态加条件,推荐用三元判断或变量传入:
$map = [];<br> if (!empty($status)) $map['status'] = $status;<br> if (!empty($keyword)) $map['name'] = ['like', "%{$keyword}%"];<br> Db::name('user')->where($map)->select();- 也可用
whereWhen()(V6.1+)自动跳过空值:->whereWhen($status, ['status' => $status])



















