查询构造器
- 简介
- 执行数据库查询
- Select 语句
- 原始表达式
- Join
- Union
- 基础 Where 子句
- 进阶 Where 子句
- 排序、分组、Limit 和 Offset
- 条件子句
- Insert 语句
- Update 语句
- Delete 语句
- 悲观锁
- 可复用的查询组件
- 调试
简介
Laravel 的数据库查询构造器提供了一套便捷、流畅的接口,用来创建和运行数据库查询。它可以用来完成应用中绝大多数数据库操作,并且能完美适配 Laravel 支持的所有数据库系统。
Laravel 查询构造器使用 PDO 参数绑定来保护应用免受 SQL 注入攻击。作为查询绑定传给查询构造器的字符串不需要再做过滤或转义。
注意
PDO 不支持绑定列名。因此,永远不要让用户输入决定查询里引用的列名,包括「order by」使用的列。
执行数据库查询
获取表中的所有行
你可以用 DB 门面提供的 table() 方法来开始一个查询。table() 方法会返回一个针对指定表的流式查询构造器实例,让你可以链式追加更多约束,最后通过 get() 方法拿到查询结果:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;
class UserController extends Controller
{
/**
* Show a list of all of the application's users.
*/
public function index(): View
{
$users = DB::table('users')->get();
return view('user.index', ['users' => $users]);
}
}
get() 方法返回一个 Illuminate\Support\Collection 实例,里面装着查询结果,其中每个结果都是一个 PHP stdClass 对象。你可以把列名当作对象属性来访问对应值:
use Illuminate\Support\Facades\DB;
$users = DB::table('users')->get();
foreach ($users as $user) {
echo $user->name;
}
信息
Laravel 集合提供了各种功能强大的映射与归约方法。想深入了解 Laravel 集合,请查阅集合文档。
获取单行或单列
如果你只需要从数据库表中取一行,可以使用 DB 门面的 first() 方法。这个方法会返回一个 stdClass 对象:
$user = DB::table('users')->where('name', 'John')->first();
return $user->email;
如果你想在找不到匹配记录时抛出 Illuminate\Database\RecordNotFoundException 异常,可以使用 firstOrFail() 方法。当 RecordNotFoundException 没被捕获时,会自动向客户端返回 404 HTTP 响应:
$user = DB::table('users')->where('name', 'John')->firstOrFail();
如果你不需要整行,只想从记录中取单个值,可以用 value() 方法。它会直接返回该列的值:
$email = DB::table('users')->where('name', 'John')->value('email');
要按 id 列的值查询单行,可以使用 find() 方法:
$user = DB::table('users')->find(3);
获取某列的值列表
如果你想拿到某一列所有值组成的 Illuminate\Support\Collection,可以使用 pluck() 方法。下面这个例子里我们取出所有用户的 title 字段:
use Illuminate\Support\Facades\DB;
$titles = DB::table('users')->pluck('title');
foreach ($titles as $title) {
echo $title;
}
你还可以通过 pluck() 的第二个参数,指定用哪一列作为结果集合的键:
$titles = DB::table('users')->pluck('title', 'name');
foreach ($titles as $name => $title) {
echo $title;
}
分块处理结果
如果你需要处理成千上万条数据库记录,可以考虑使用 DB 门面提供的 chunk() 方法。这个方法每次取出一小块结果,然后把每块交给闭包处理。举个例子,我们把 users 表分成每次 100 条来处理:
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
DB::table('users')->orderBy('id')->chunk(100, function (Collection $users) {
foreach ($users as $user) {
// ...
}
});
在闭包里返回 false 可以停止后续分块处理:
DB::table('users')->orderBy('id')->chunk(100, function (Collection $users) {
// Process the records...
return false;
});
如果你在分块时会更新数据库记录,那么分块结果可能会以意想不到的方式发生变化。如果你打算在分块过程中更新取到的记录,最好改用 chunkById() 方法。这个方法会根据记录的主键自动分页:
DB::table('users')->where('active', false)
->chunkById(100, function (Collection $users) {
foreach ($users as $user) {
DB::table('users')
->where('id', $user->id)
->update(['active' => true]);
}
});
因为 chunkById() 和 lazyById() 会在被执行的查询里追加自己的「where」条件,通常你应该把自己的条件放进闭包里逻辑分组:
DB::table('users')->where(function ($query) {
$query->where('credits', 1)->orWhere('credits', 2);
})->chunkById(100, function (Collection $users) {
foreach ($users as $user) {
DB::table('users')
->where('id', $user->id)
->update(['credits' => 3]);
}
});
注意
在分块回调中更新或删除记录时,对主键或外键的任何更改都可能影响分块查询,从而导致某些记录被漏掉。
惰性流式处理
lazy() 方法的工作方式和 chunk 方法类似,都是按块执行查询。但它不会把每块传给回调,而是返回一个 LazyCollection,让你可以把结果当作单一的数据流来使用:
use Illuminate\Support\Facades\DB;
DB::table('users')->orderBy('id')->lazy()->each(function (object $user) {
// ...
});
同样地,如果你打算在遍历过程中更新取到的记录,最好使用 lazyById() 或 lazyByIdDesc() 方法。它们会根据记录的主键自动分页:
DB::table('users')->where('active', false)
->lazyById()->each(function (object $user) {
DB::table('users')
->where('id', $user->id)
->update(['active' => true]);
});
注意
在遍历过程中更新或删除记录时,对主键或外键的任何更改都可能影响分块查询,从而导致某些记录被漏掉。
聚合函数
查询构造器还提供了一系列用于获取聚合值的方法,比如 count、max、min、avg 和 sum。你可以在构造好查询后调用任意一个:
use Illuminate\Support\Facades\DB;
$users = DB::table('users')->count();
$price = DB::table('orders')->max('price');
当然,你可以把这些方法和其他子句组合起来,精细地控制聚合值的计算方式:
$price = DB::table('orders')
->where('finalized', 1)
->avg('price');
判断记录是否存在
不用 count() 方法判断是否有满足查询约束的记录,你可以直接使用 exists() 和 doesntExist():
if (DB::table('orders')->where('finalized', 1)->exists()) {
// ...
}
if (DB::table('orders')->where('finalized', 1)->doesntExist()) {
// ...
}
Select 语句
指定 Select 子句
你可能并不总想选出数据库表里的所有列。使用 select() 方法,你可以为查询指定自定义的「select」子句:
use Illuminate\Support\Facades\DB;
$users = DB::table('users')
->select('name', 'email as user_email')
->get();
distinct() 方法可以强制查询返回不重复的结果:
$users = DB::table('users')->distinct()->get();
如果你已经有了一个查询构造器实例,想在原有 select 子句上再加一列,可以使用 addSelect() 方法:
$query = DB::table('users')->select('name');
$users = $query->addSelect('age')->get();
原始表达式
有时你需要把任意字符串插入查询中。要创建原始字符串表达式,可以使用 DB 门面提供的 raw() 方法:
$users = DB::table('users')
->select(DB::raw('count(*) as user_count, status'))
->where('status', '<>', 1)
->groupBy('status')
->get();
注意
原始语句会以字符串形式注入到查询里,一定要格外小心避免造成 SQL 注入漏洞。
原始方法
除了使用 DB::raw() 方法之外,你还可以使用下面这些方法把原始表达式插入到查询的不同部分。注意,Laravel 无法保证任何使用原始表达式的查询都能防范 SQL 注入漏洞。
selectRaw
selectRaw() 方法可以代替 addSelect(DB::raw(/* ... */))。它接受一个可选的绑定数组作为第二个参数:
$orders = DB::table('orders')
->selectRaw('price * ? as price_with_tax', [1.0825])
->get();
whereRaw / orWhereRaw
whereRaw() 和 orWhereRaw() 方法用于向查询注入原始的「where」子句。它们接受一个可选的绑定数组作为第二个参数:
$orders = DB::table('orders')
->whereRaw('price > IF(state = "TX", ?, 100)', [200])
->get();
havingRaw / orHavingRaw
havingRaw() 和 orHavingRaw() 方法可以为「having」子句提供原始字符串值。它们接受一个可选的绑定数组作为第二个参数:
$orders = DB::table('orders')
->select('department', DB::raw('SUM(price) as total_sales'))
->groupBy('department')
->havingRaw('SUM(price) > ?', [2500])
->get();
orderByRaw
orderByRaw() 方法可以为「order by」子句提供原始字符串值:
$orders = DB::table('orders')
->orderByRaw('updated_at - created_at DESC')
->get();
groupByRaw
groupByRaw() 方法可以为 group by 子句提供原始字符串值:
$orders = DB::table('orders')
->select('city', 'state')
->groupByRaw('city, state')
->get();
Join
内连接
查询构造器也可以用来为查询添加 join 子句。要执行一个基本的「内连接」,可以在查询构造器实例上调用 join() 方法。传给 join() 方法的第一个参数是需要连接的表名,剩下的参数用来指定连接的列约束。你甚至可以在单个查询里连接多张表:
use Illuminate\Support\Facades\DB;
$users = DB::table('users')
->join('contacts', 'users.id', '=', 'contacts.user_id')
->join('orders', 'users.id', '=', 'orders.user_id')
->select('users.*', 'contacts.phone', 'orders.price')
->get();
左连接 / 右连接
如果你想执行「左连接」或「右连接」而不是「内连接」,可以使用 leftJoin() 或 rightJoin() 方法。它们的签名与 join() 相同:
$users = DB::table('users')
->leftJoin('posts', 'users.id', '=', 'posts.user_id')
->get();
$users = DB::table('users')
->rightJoin('posts', 'users.id', '=', 'posts.user_id')
->get();
交叉连接
可以使用 crossJoin() 方法执行「交叉连接」。交叉连接会在第一个表和被连接的表之间生成笛卡尔积:
$sizes = DB::table('sizes')
->crossJoin('colors')
->get();
进阶 Join 子句
你还可以指定更复杂的 join 子句。开始使用时,把闭包作为 join() 方法的第二个参数传进去。闭包会收到一个 Illuminate\Database\Query\JoinClause 实例,让你可以为「join」子句指定约束:
DB::table('users')
->join('contacts', function (JoinClause $join) {
$join->on('users.id', '=', 'contacts.user_id')->orOn(/* ... */);
})
->get();
如果你想在 join 中使用「where」子句,可以使用 JoinClause 实例提供的 where() 和 orWhere() 方法。这两个方法不再是比较两列,而是把列和一个值做比较:
DB::table('users')
->join('contacts', function (JoinClause $join) {
$join->on('users.id', '=', 'contacts.user_id')
->where('contacts.user_id', '>', 5);
})
->get();
子查询 Join
你可以使用 joinSub()、leftJoinSub() 和 rightJoinSub() 方法,把一个查询与子查询做连接。每个方法都接收三个参数:子查询、表别名以及一个用于定义关联列的闭包。下面这个例子里,我们要取出用户集合,每个用户记录还包含该用户最近发布博客文章的 created_at 时间戳:
$latestPosts = DB::table('posts')
->select('user_id', DB::raw('MAX(created_at) as last_post_created_at'))
->where('is_published', true)
->groupBy('user_id');
$users = DB::table('users')
->joinSub($latestPosts, 'latest_posts', function (JoinClause $join) {
$join->on('users.id', '=', 'latest_posts.user_id');
})->get();
横向连接(Lateral Join)
注意
横向连接目前仅在 PostgreSQL、MySQL 8.0.14+ 和 SQL Server 上受支持。
你可以使用 joinLateral() 和 leftJoinLateral() 方法对子查询执行「横向连接」。它们各自接收两个参数:子查询和表别名。连接条件应写在子查询的 where 子句里。横向连接会为每一行分别求值,并可以引用子查询之外的列。
在这个例子里,我们要取出用户集合以及每个用户最近发布的 3 篇博客文章。每个用户最多会在结果集中产生 3 行——每篇最新博客一行。连接条件通过子查询里的 whereColumn 子句指定,它引用了当前用户行:
$latestPosts = DB::table('posts')
->select('id as post_id', 'title as post_title', 'created_at as post_created_at')
->whereColumn('user_id', 'users.id')
->orderBy('created_at', 'desc')
->limit(3);
$users = DB::table('users')
->joinLateral($latestPosts, 'latest_posts')
->get();
Union
查询构造器还提供了一个便捷方法,可以把两个或多个查询「union」在一起。比如你可以先建一个查询,再用 union() 方法把它和其他查询联合起来:
use Illuminate\Support\Facades\DB;
$usersWithoutFirstName = DB::table('users')
->whereNull('first_name');
$users = DB::table('users')
->whereNull('last_name')
->union($usersWithoutFirstName)
->get();
除了 union(),查询构造器还提供了 unionAll() 方法。使用 unionAll() 联合的查询不会去重。unionAll() 与 union() 的方法签名相同。
基础 Where 子句
Where 子句
你可以使用查询构造器的 where() 方法向查询添加「where」子句。最基本的 where() 调用需要三个参数。第一个是列名。第二个是操作符——可以是数据库支持的任意操作符。第三个是要与列值比较的值。
比如,下面这个查询会取出 votes 列等于 100 且 age 列大于 35 的用户:
$users = DB::table('users')
->where('votes', '=', 100)
->where('age', '>', 35)
->get();
为了方便,如果你想校验某列 = 某个值,可以直接把这个值作为 where() 方法的第二个参数,Laravel 会默认使用 = 操作符:
$users = DB::table('users')->where('votes', 100)->get();
你还可以把关联数组传给 where() 方法,快速对多个列做等值查询:
$users = DB::table('users')->where([
'first_name' => 'Jane',
'last_name' => 'Doe',
])->get();
如上所述,你可以使用数据库系统支持的任何操作符:
$users = DB::table('users')
->where('votes', '>=', 100)
->get();
$users = DB::table('users')
->where('votes', '<>', 100)
->get();
$users = DB::table('users')
->where('name', 'like', 'T%')
->get();
你也可以给 where() 函数传一个条件数组。数组的每个元素都应该是一个数组,包含 where() 方法通常接受的三个参数:
$users = DB::table('users')->where([
['status', '=', '1'],
['subscribed', '<>', '1'],
])->get();
注意
PDO 不支持绑定列名。因此,永远不要让用户输入决定查询里引用的列名,包括「order by」使用的列。
注意
MySQL 与 MariaDB 在字符串与数字比较时会自动把字符串转为整数。在这个过程中,非数字字符串会被转成 0,可能导致意想不到的结果。举例来说,如果表里 secret 列的值是 aaa,执行 User::where('secret', 0) 会把该行返回。为避免这种情况,请确保在查询前把所有值强制转成对应类型。
Or Where 子句
链式调用查询构造器的 where() 方法时,「where」子句会用 and 操作符连接在一起。而使用 orWhere() 方法则用 or 操作符把子句连到查询上。orWhere() 与 where() 接受相同的参数:
$users = DB::table('users')
->where('votes', '>', 100)
->orWhere('name', 'John')
->get();
如果你需要把一个「or」条件用括号分组,可以把闭包作为 orWhere() 方法的第一个参数:
use Illuminate\Database\Query\Builder;
$users = DB::table('users')
->where('votes', '>', 100)
->orWhere(function (Builder $query) {
$query->where('name', 'Abigail')
->where('votes', '>', 50);
})
->get();
上面的例子会产生下面这条 SQL:
select * from users where votes > 100 or (name = 'Abigail' and votes > 50)
注意
在使用全局作用域时,为避免意外行为,orWhere 调用应始终显式分组。
Where Not 子句
whereNot() 和 orWhereNot() 方法可以用于对一组查询约束取反。比如下面这个查询会排除处于清仓状态或价格低于 10 的产品:
$products = DB::table('products')
->whereNot(function (Builder $query) {
$query->where('clearance', true)
->orWhere('price', '<', 10);
})
->get();
Where Any / All / None 子句
有时你需要给多个列施加同样的查询约束。比如你想取出「一组列中任意一列 LIKE 某个值」的所有记录,可以用 whereAny() 方法实现:
$users = DB::table('users')
->where('active', true)
->whereAny([
'name',
'email',
'phone',
], 'like', 'Example%')
->get();
上面这条查询会生成下面的 SQL:
SELECT *
FROM users
WHERE active = true AND (
name LIKE 'Example%' OR
email LIKE 'Example%' OR
phone LIKE 'Example%'
)
同样地,whereAll() 方法可以取出「给定所有列都匹配同一约束」的记录:
$posts = DB::table('posts')
->where('published', true)
->whereAll([
'title',
'content',
], 'like', '%Laravel%')
->get();
上面这条查询会生成下面的 SQL:
SELECT *
FROM posts
WHERE published = true AND (
title LIKE '%Laravel%' AND
content LIKE '%Laravel%'
)
whereNone() 方法可以取出「给定列都不匹配约束」的记录:
$albums = DB::table('albums')
->where('published', true)
->whereNone([
'title',
'lyrics',
'tags',
], 'like', '%explicit%')
->get();
上面这条查询会生成下面的 SQL:
SELECT *
FROM albums
WHERE published = true AND NOT (
title LIKE '%explicit%' OR
lyrics LIKE '%explicit%' OR
tags LIKE '%explicit%'
)
JSON Where 子句
Laravel 也支持在提供 JSON 列类型的数据库上查询 JSON 列。目前包括 MariaDB 10.3+、MySQL 8.0+、PostgreSQL 12.0+、SQL Server 2017+ 和 SQLite 3.39.0+。查询 JSON 列时使用 -> 操作符:
$users = DB::table('users')
->where('preferences->dining->meal', 'salad')
->get();
$users = DB::table('users')
->whereIn('preferences->dining->meal', ['pasta', 'salad', 'sandwiches'])
->get();
可以使用 whereJsonContains() 和 whereJsonDoesntContain() 方法查询 JSON 数组:
$users = DB::table('users')
->whereJsonContains('options->languages', 'en')
->get();
$users = DB::table('users')
->whereJsonDoesntContain('options->languages', 'en')
->get();
如果你的应用使用的是 MariaDB、MySQL 或 PostgreSQL 数据库,可以给 whereJsonContains() 和 whereJsonDoesntContain() 传一个值数组:
$users = DB::table('users')
->whereJsonContains('options->languages', ['en', 'de'])
->get();
$users = DB::table('users')
->whereJsonDoesntContain('options->languages', ['en', 'de'])
->get();
此外,你可以用 whereJsonContainsKey() 或 whereJsonDoesntContainKey() 方法取出「包含或不包含指定 JSON 键」的结果:
$users = DB::table('users')
->whereJsonContainsKey('preferences->dietary_requirements')
->get();
$users = DB::table('users')
->whereJsonDoesntContainKey('preferences->dietary_requirements')
->get();
最后,可以使用 whereJsonLength() 方法按长度查询 JSON 数组:
$users = DB::table('users')
->whereJsonLength('options->languages', 0)
->get();
$users = DB::table('users')
->whereJsonLength('options->languages', '>', 1)
->get();
其他 Where 子句
whereLike / orWhereLike / whereNotLike / orWhereNotLike
whereLike() 方法允许你为查询添加「LIKE」子句用于模式匹配。这些方法提供了一种与数据库无关的字符串匹配查询方式,并且可以切换大小写敏感性。默认情况下字符串匹配不区分大小写:
$users = DB::table('users')
->whereLike('name', '%John%')
->get();
你可以通过 caseSensitive 参数启用区分大小写的搜索:
$users = DB::table('users')
->whereLike('name', '%John%', caseSensitive: true)
->get();
orWhereLike() 方法用于添加带 LIKE 条件的「or」子句:
$users = DB::table('users')
->where('votes', '>', 100)
->orWhereLike('name', '%John%')
->get();
whereNotLike() 方法用于向查询添加「NOT LIKE」子句:
$users = DB::table('users')
->whereNotLike('name', '%John%')
->get();
同样地,可以使用 orWhereNotLike() 添加带 NOT LIKE 条件的「or」子句:
$users = DB::table('users')
->where('votes', '>', 100)
->orWhereNotLike('name', '%John%')
->get();
注意
whereLike 的大小写敏感选项目前不支持 SQL Server。
whereIn / whereNotIn / orWhereIn / orWhereNotIn
whereIn() 方法验证某列的值是否包含在给定数组中:
$users = DB::table('users')
->whereIn('id', [1, 2, 3])
->get();
whereNotIn() 方法验证某列的值是否不在给定数组中:
$users = DB::table('users')
->whereNotIn('id', [1, 2, 3])
->get();
你还可以给 whereIn() 方法的第二个参数传一个查询对象:
$activeUsers = DB::table('users')->select('id')->where('is_active', 1);
$comments = DB::table('comments')
->whereIn('user_id', $activeUsers)
->get();
上面的例子会产生下面这条 SQL:
select * from comments where user_id in (
select id
from users
where is_active = 1
)
注意
如果要向查询中添加一个很大的整数绑定数组,可以使用 whereIntegerInRaw 或 whereIntegerNotInRaw 方法大幅降低内存占用。
whereBetween / orWhereBetween
whereBetween() 方法验证某列的值是否在两个值之间:
$users = DB::table('users')
->whereBetween('votes', [1, 100])
->get();
whereNotBetween / orWhereNotBetween
whereNotBetween() 方法验证某列的值是否在两个值范围之外:
$users = DB::table('users')
->whereNotBetween('votes', [1, 100])
->get();
whereBetweenColumns / whereNotBetweenColumns / orWhereBetweenColumns / orWhereNotBetweenColumns
whereBetweenColumns() 方法验证某列的值是否位于同一表行中两个列的值之间:
$patients = DB::table('patients')
->whereBetweenColumns('weight', ['minimum_allowed_weight', 'maximum_allowed_weight'])
->get();
whereNotBetweenColumns() 方法验证某列的值是否位于同一表行中两个列的值范围之外:
$patients = DB::table('patients')
->whereNotBetweenColumns('weight', ['minimum_allowed_weight', 'maximum_allowed_weight'])
->get();
whereValueBetween / whereValueNotBetween / orWhereValueBetween / orWhereValueNotBetween
whereValueBetween() 方法验证给定值是否位于同一表行中同类型的两列值之间:
$products = DB::table('products')
->whereValueBetween(100, ['min_price', 'max_price'])
->get();
whereValueNotBetween() 方法验证给定值是否位于同一表行中两列值范围之外:
$products = DB::table('products')
->whereValueNotBetween(100, ['min_price', 'max_price'])
->get();
whereNull / whereNotNull / orWhereNull / orWhereNotNull
whereNull() 方法验证给定列的值是否为 NULL:
$users = DB::table('users')
->whereNull('updated_at')
->get();
whereNotNull() 方法验证列的值是否不为 NULL:
$users = DB::table('users')
->whereNotNull('updated_at')
->get();
whereNullSafeEquals / orWhereNullSafeEquals
whereNullSafeEquals() 和 orWhereNullSafeEquals() 方法可以把列的值与给定值做比较,并把两个 NULL 视为相等:
$lastLoginIp = $request->input('last_login_ip');
$users = DB::table('users')
->whereNullSafeEquals('last_login_ip', $lastLoginIp)
->get();
whereDate / whereMonth / whereDay / whereYear / whereTime
whereDate() 方法用于将列的值与日期做比较:
$users = DB::table('users')
->whereDate('created_at', '2016-12-31')
->get();
whereMonth() 方法用于将列的值与指定月份做比较:
$users = DB::table('users')
->whereMonth('created_at', '12')
->get();
whereDay() 方法用于将列的值与月份中的指定日做比较:
$users = DB::table('users')
->whereDay('created_at', '31')
->get();
whereYear() 方法用于将列的值与指定年份做比较:
$users = DB::table('users')
->whereYear('created_at', '2016')
->get();
whereTime() 方法用于将列的值与指定时间做比较:
$users = DB::table('users')
->whereTime('created_at', '=', '11:20:45')
->get();
wherePast / whereFuture / whereToday / whereBeforeToday / whereAfterToday
wherePast() 和 whereFuture() 方法可以用于判断某列的值是否在过去或将来:
$invoices = DB::table('invoices')
->wherePast('due_at')
->get();
$invoices = DB::table('invoices')
->whereFuture('due_at')
->get();
whereNowOrPast() 和 whereNowOrFuture() 方法可以判断某列的值是否在过去或将来(包含当前日期与时间):
$invoices = DB::table('invoices')
->whereNowOrPast('due_at')
->get();
$invoices = DB::table('invoices')
->whereNowOrFuture('due_at')
->get();
whereToday()、whereBeforeToday() 和 whereAfterToday() 方法可以分别判断某列的值是否为今天、今天之前或今天之后:
$invoices = DB::table('invoices')
->whereToday('due_at')
->get();
$invoices = DB::table('invoices')
->whereBeforeToday('due_at')
->get();
$invoices = DB::table('invoices')
->whereAfterToday('due_at')
->get();
类似地,whereTodayOrBefore() 和 whereTodayOrAfter() 方法可以判断某列的值是否为今天之前或今天之后(包含今天):
$invoices = DB::table('invoices')
->whereTodayOrBefore('due_at')
->get();
$invoices = DB::table('invoices')
->whereTodayOrAfter('due_at')
->get();
whereColumn / orWhereColumn
whereColumn() 方法可以用来验证两列是否相等:
$users = DB::table('users')
->whereColumn('first_name', 'last_name')
->get();
也可以给 whereColumn() 方法传比较操作符:
$users = DB::table('users')
->whereColumn('updated_at', '>', 'created_at')
->get();
也可以给 whereColumn() 方法传一个列比较数组,条件之间用 and 操作符连接:
$users = DB::table('users')
->whereColumn([
['first_name', '=', 'last_name'],
['updated_at', '>', 'created_at'],
])->get();
逻辑分组
有时你需要把若干「where」子句用括号分组,才能实现查询期望的逻辑分组。实际上,一般都应把对 orWhere() 方法的调用用括号分组,以免出现意想不到的查询行为。要做到这一点,把闭包传给 where() 方法即可:
$users = DB::table('users')
->where('name', '=', 'John')
->where(function (Builder $query) {
$query->where('votes', '>', 100)
->orWhere('title', '=', 'Admin');
})
->get();
可以看到,把闭包传给 where() 方法就是在告诉查询构造器开始一个约束分组。闭包会收到一个查询构造器实例,你可以用它设置这一括号分组内要包含的约束。上面这个例子会产生下面这条 SQL:
select * from users where name = 'John' and (votes > 100 or title = 'Admin')
注意
在使用全局作用域时,为避免意外行为,orWhere 调用应始终显式分组。
进阶 Where 子句
Where Exists 子句
whereExists() 方法允许你编写「where exists」SQL 子句。它接收一个闭包,闭包会收到查询构造器实例,你可以在里面定义要放到「exists」子句中的查询:
$users = DB::table('users')
->whereExists(function (Builder $query) {
$query->select(DB::raw(1))
->from('orders')
->whereColumn('orders.user_id', 'users.id');
})
->get();
或者,你也可以给 whereExists() 方法直接传一个查询对象来代替闭包:
$orders = DB::table('orders')
->select(DB::raw(1))
->whereColumn('orders.user_id', 'users.id');
$users = DB::table('users')
->whereExists($orders)
->get();
上面两个例子都会产生下面这条 SQL:
select * from users
where exists (
select 1
from orders
where orders.user_id = users.id
)
子查询 Where 子句
有时你需要构造一个「where」子句,把子查询的结果与给定值做比较。你可以给 where() 方法传闭包和值来实现。比如下面这个查询会取出所有最近拥有指定类型「会员资格」的用户:
use App\Models\User;
use Illuminate\Database\Query\Builder;
$users = User::where(function (Builder $query) {
$query->select('type')
->from('membership')
->whereColumn('membership.user_id', 'users.id')
->orderByDesc('membership.start_date')
->limit(1);
}, 'Pro')->get();
或者,你可能需要构造一个「where」子句,把某列与子查询结果做比较。可以给 where() 方法传列名、操作符和闭包来实现。比如下面这个查询会取出所有金额低于平均值的收入记录:
use App\Models\Income;
use Illuminate\Database\Query\Builder;
$incomes = Income::where('amount', '<', function (Builder $query) {
$query->selectRaw('avg(i.amount)')->from('incomes as i');
})->get();
全文 Where 子句
注意
全文 where 子句目前仅在 MariaDB、MySQL 和 PostgreSQL 上受支持。
whereFullText() 和 orWhereFullText() 方法可以为拥有全文索引的列添加全文「where」子句。Laravel 会把它们转换成底层数据库系统对应的 SQL。比如在使用 MariaDB 或 MySQL 的应用中,会生成 MATCH AGAINST 子句:
$users = DB::table('users')
->whereFullText('bio', 'web developer')
->get();
向量相似度子句
信息
向量相似度子句目前仅支持使用 pgvector 扩展的 PostgreSQL 连接。关于向量列与索引的定义方式,请查阅迁移文档。
whereVectorSimilarTo() 方法通过余弦相似度过滤结果,并按相关性排序。minSimilarity 阈值取值范围为 0.0 到 1.0,1.0 表示完全一致:
$documents = DB::table('documents')
->whereVectorSimilarTo('embedding', $queryEmbedding, minSimilarity: 0.4)
->limit(10)
->get();
如果向量参数传的是普通字符串,Laravel 会自动通过 Laravel AI SDK 为其生成 embeddings:
$documents = DB::table('documents')
->whereVectorSimilarTo('embedding', 'Best wineries in Napa Valley')
->limit(10)
->get();
默认情况下,whereVectorSimilarTo() 还会按距离对结果排序(最相似的排最前)。可以通过给 order 参数传 false 关闭这个排序:
$documents = DB::table('documents')
->whereVectorSimilarTo('embedding', $queryEmbedding, minSimilarity: 0.4, order: false)
->orderBy('created_at', 'desc')
->limit(10)
->get();
如果你需要更精细的控制,可以单独使用 selectVectorDistance()、whereVectorDistanceLessThan() 和 orderByVectorDistance() 方法:
$documents = DB::table('documents')
->select('*')
->selectVectorDistance('embedding', $queryEmbedding, as: 'distance')
->whereVectorDistanceLessThan('embedding', $queryEmbedding, maxDistance: 0.3)
->orderByVectorDistance('embedding', $queryEmbedding)
->limit(10)
->get();
在使用 PostgreSQL 时,创建 vector 列之前必须先加载 pgvector 扩展:
Schema::ensureVectorExtensionExists();
排序、分组、Limit 和 Offset
排序
orderBy 方法
orderBy() 方法允许你按指定列对查询结果排序。第一个参数是你想排序的列,第二个参数决定排序方向,取值可以是 asc 或 desc:
$users = DB::table('users')
->orderBy('name', 'desc')
->get();
要按多列排序,只需要按需多次调用 orderBy() 即可:
$users = DB::table('users')
->orderBy('name', 'desc')
->orderBy('email', 'asc')
->get();
排序方向可选,默认升序。如果想降序排列,可以给 orderBy() 指定第二个参数,或者直接用 orderByDesc():
$users = DB::table('users')
->orderByDesc('verified_at')
->get();
最后,配合 -> 操作符,还能按 JSON 列中的值排序:
$corporations = DB::table('corporations')
->where('country', 'US')
->orderBy('location->state')
->get();
latest 与 oldest 方法
latest() 与 oldest() 方法可以方便地按日期排序。默认按表的 created_at 列排序,你也可以传入想排序的列名:
$user = DB::table('users')
->latest()
->first();
随机排序
inRandomOrder() 方法可以对查询结果做随机排序。比如你可以用它随机取出一位用户:
$randomUser = DB::table('users')
->inRandomOrder()
->first();
移除现有的排序
reorder() 方法会移除此前应用到查询上的所有「order by」子句:
$query = DB::table('users')->orderBy('name');
$unorderedUsers = $query->reorder()->get();
调用 reorder() 时可以传入列名和方向,用来先清空所有现有「order by」子句、再对查询应用全新的排序:
$query = DB::table('users')->orderBy('name');
$usersOrderedByEmail = $query->reorder('email', 'desc')->get();
为了方便,你还可以使用 reorderDesc() 方法将结果按降序重新排列:
$query = DB::table('users')->orderBy('name');
$usersOrderedByEmail = $query->reorderDesc('email')->get();
分组
groupBy 与 having 方法
如你所料,groupBy() 与 having() 方法可以对查询结果分组。having() 的方法签名与 where() 类似:
$users = DB::table('users')
->groupBy('account_id')
->having('account_id', '>', 100)
->get();
你可以用 havingBetween() 方法过滤指定范围内的结果:
$report = DB::table('orders')
->selectRaw('count(id) as number_of_orders, customer_id')
->groupBy('customer_id')
->havingBetween('number_of_orders', [5, 15])
->get();
groupBy() 方法可以接收多个参数,按多列分组:
$users = DB::table('users')
->groupBy('first_name', 'status')
->having('account_id', '>', 100)
->get();
要构造更复杂的 having 语句,请参考 havingRaw 方法。
Limit 与 Offset
你可以使用 limit() 和 offset() 方法来限制查询返回的结果数量,或跳过指定数量的结果:
$users = DB::table('users')
->offset(10)
->limit(5)
->get();
条件子句
有时你可能希望某些查询子句根据另一个条件是否满足来应用。比如,只有当传入的 HTTP 请求里存在某个字段时,才追加一条 where 语句。这可以通过 when() 方法实现:
$role = $request->input('role');
$users = DB::table('users')
->when($role, function (Builder $query, string $role) {
$query->where('role_id', $role);
})
->get();
when() 方法只有在第一个参数为 true 时才执行给定闭包。如果第一个参数为 false,闭包不会执行。所以上面这个例子里,只有当请求中存在 role 字段且求值为 true 时,when() 的闭包才会被调用。
你可以给 when() 方法传入第三个闭包作为第三个参数,只有当第一个参数求值为 false 时才会执行。为了说明这个特性的用法,我们用它来配置查询的默认排序:
$sortByVotes = $request->boolean('sort_by_votes');
$users = DB::table('users')
->when($sortByVotes, function (Builder $query, bool $sortByVotes) {
$query->orderBy('votes');
}, function (Builder $query) {
$query->orderBy('name');
})
->get();
Insert 语句
查询构造器还提供了 insert() 方法,可以用来向数据库表插入记录。insert() 方法接收一个包含列名和值的数组:
DB::table('users')->insert([
'email' => 'kayla@example.com',
'votes' => 0
]);
你可以通过传入嵌套数组一次插入多条记录。每个内层数组代表要插入表中的一条记录:
DB::table('users')->insert([
['email' => 'picard@example.com', 'votes' => 0],
['email' => 'janeway@example.com', 'votes' => 0],
]);
insertOrIgnore() 方法会忽略插入过程中的错误。使用这个方法时要注意,重复记录错误会被忽略,某些其他类型的错误也可能被忽略——具体取决于数据库引擎。比如,insertOrIgnore() 会绕过 MySQL 的严格模式:
DB::table('users')->insertOrIgnore([
['id' => 1, 'email' => 'sisko@example.com'],
['id' => 2, 'email' => 'archer@example.com'],
]);
insertUsing() 方法会向表中插入新记录,同时用子查询来决定要插入哪些数据:
DB::table('pruned_users')->insertUsing([
'id', 'name', 'email', 'email_verified_at'
], DB::table('users')->select(
'id', 'name', 'email', 'email_verified_at'
)->where('updated_at', '<=', now()->minus(months: 1)));
自增 ID
如果表有自增 id,使用 insertGetId() 方法可以在插入记录后立即取回 ID:
$id = DB::table('users')->insertGetId(
['email' => 'john@example.com', 'votes' => 0]
);
注意
在 PostgreSQL 中使用 insertGetId 时,方法默认自增列名为 id。如果你想从其他「sequence」取回 ID,可以把列名作为第二个参数传给 insertGetId。
Upsert
upsert() 方法会插入不存在的记录,并把已存在的记录用你指定的值更新。第一个参数是要插入或更新的值数组,第二个参数列出用于在关联表中唯一标识记录的列名,第三个(也是最后一个)参数是如果匹配到已存在记录时应该更新的列数组:
DB::table('flights')->upsert(
[
['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99],
['departure' => 'Chicago', 'destination' => 'New York', 'price' => 150]
],
['departure', 'destination'],
['price']
);
在上面的例子里,Laravel 会尝试插入两条记录。如果已经存在 departure 和 destination 相同的记录,Laravel 会更新那条记录的 price 列。
注意
除 SQL Server 外,所有数据库都要求 upsert 方法第二个参数指定的列具有「主键」或「唯一」索引。此外,MariaDB 和 MySQL 数据库驱动会忽略 upsert 方法的第二个参数,始终使用表的「主键」和「唯一」索引来检测已存在的记录。
Update 语句
除了向数据库插入记录,查询构造器还可以用 update() 方法更新已有记录。update() 方法与 insert() 一样,接收一个列名与值成对组成的数组,用于指定要更新的列。update() 方法返回受影响的行数。你可以使用 where 子句约束 update 查询:
$affected = DB::table('users')
->where('id', 1)
->update(['votes' => 1]);
Update 或 Insert
有时你想更新数据库里已存在的记录,或者在找不到匹配记录时创建它。这种场景下可以使用 updateOrInsert() 方法。它接收两个参数:用于查找记录的条件数组,以及指示要更新的列名与值成对组成的数组。
updateOrInsert() 方法会先根据第一个参数中的列值组合尝试定位匹配的数据库记录。如果记录存在,就用第二个参数中的值更新;如果找不到,就用两个参数合并后的属性插入一条新记录:
DB::table('users')
->updateOrInsert(
['email' => 'john@example.com', 'name' => 'John'],
['votes' => '2']
);
你也可以给 updateOrInsert() 方法传一个闭包,根据是否存在匹配记录来定制要更新或插入的属性:
DB::table('users')->updateOrInsert(
['user_id' => $user_id],
fn ($exists) => $exists ? [
'name' => $data['name'],
'email' => $data['email'],
] : [
'name' => $data['name'],
'email' => $data['email'],
'marketable' => true,
],
);
更新 JSON 字段
更新 JSON 列时,应使用 -> 语法更新 JSON 对象中的对应键。此操作在 MariaDB 10.3+、MySQL 5.7+ 和 PostgreSQL 9.5+ 上支持:
$affected = DB::table('users')
->where('id', 1)
->update(['options->enabled' => true]);
自增与自减
查询构造器还提供了便捷方法来对指定列的值做自增或自减。这两个方法至少接收一个参数:要修改的列。可以传第二个参数来指定自增或自减的幅度:
DB::table('users')->increment('votes');
DB::table('users')->increment('votes', 5);
DB::table('users')->decrement('votes');
DB::table('users')->decrement('votes', 5);
如需在自增或自减操作中同时更新其他列,可以额外指定:
DB::table('users')->increment('votes', 1, ['name' => 'John']);
此外,还可以使用 incrementEach() 和 decrementEach() 方法一次性对多列做自增或自减:
DB::table('users')->incrementEach([
'votes' => 5,
'balance' => 100,
]);
Delete 语句
查询构造器的 delete() 方法可以用来删除表中的记录,返回受影响的行数。调用 delete() 前可以先加「where」子句来约束要删除的记录:
$deleted = DB::table('users')->delete();
$deleted = DB::table('users')->where('votes', '>', 100)->delete();
悲观锁
查询构造器还包含一些函数,帮你在执行 select 语句时实现「悲观锁」。要执行一条带「共享锁」的语句,可以调用 sharedLock() 方法。共享锁会阻止选中的行在你的事务提交前被修改:
DB::table('users')
->where('votes', '>', 100)
->sharedLock()
->get();
或者,你也可以使用 lockForUpdate() 方法。「for update」锁会阻止选中的记录被修改,也不允许被其他共享锁选中:
DB::table('users')
->where('votes', '>', 100)
->lockForUpdate()
->get();
虽然不是强制要求,但推荐把悲观锁包在事务里。这样能保证在整个操作完成之前,取出的数据在数据库中不会被改动。一旦失败,事务会回滚所有更改,并自动释放锁:
DB::transaction(function () {
$sender = DB::table('users')
->lockForUpdate()
->find(1);
$receiver = DB::table('users')
->lockForUpdate()
->find(2);
if ($sender->balance < 100) {
throw new RuntimeException('Balance too low.');
}
DB::table('users')
->where('id', $sender->id)
->update([
'balance' => $sender->balance - 100
]);
DB::table('users')
->where('id', $receiver->id)
->update([
'balance' => $receiver->balance + 100
]);
});
可复用的查询组件
如果应用中存在重复的查询逻辑,你可以用查询构造器的 tap() 与 pipe() 方法把这些逻辑抽取到可复用对象中。假设应用中有下面两个不同的查询:
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
$destination = $request->query('destination');
DB::table('flights')
->when($destination, function (Builder $query, string $destination) {
$query->where('destination', $destination);
})
->orderByDesc('price')
->get();
// ...
$destination = $request->query('destination');
DB::table('flights')
->when($destination, function (Builder $query, string $destination) {
$query->where('destination', $destination);
})
->where('user', $request->user()->id)
->orderBy('destination')
->get();
你可能想把这些查询中通用的目的地过滤逻辑抽取成一个可复用的对象:
<?php
namespace App\Scopes;
use Illuminate\Database\Query\Builder;
class DestinationFilter
{
public function __construct(
private ?string $destination,
) {
//
}
public function __invoke(Builder $query): void
{
$query->when($this->destination, function (Builder $query) {
$query->where('destination', $this->destination);
});
}
}
然后就可以使用查询构造器的 tap() 方法把这个对象的逻辑应用到查询上:
use App\Scopes\DestinationFilter;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
DB::table('flights')
->when($destination, function (Builder $query, string $destination) { // [tl! remove]
$query->where('destination', $destination); // [tl! remove]
}) // [tl! remove]
->tap(new DestinationFilter($destination)) // [tl! add]
->orderByDesc('price')
->get();
// ...
DB::table('flights')
->when($destination, function (Builder $query, string $destination) { // [tl! remove]
$query->where('destination', $destination); // [tl! remove]
}) // [tl! remove]
->tap(new DestinationFilter($destination)) // [tl! add]
->where('user', $request->user()->id)
->orderBy('destination')
->get();
查询管道
tap() 方法始终返回查询构造器。如果你想抽取一个既执行查询又返回其他值的对象,可以改用 pipe() 方法。
考虑下面这个封装应用中通用分页逻辑的查询对象。与 DestinationFilter 只给查询附加条件不同,Paginate 对象会执行查询并返回一个分页器实例:
<?php
namespace App\Scopes;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Query\Builder;
class Paginate
{
public function __construct(
private string $sortBy = 'timestamp',
private string $sortDirection = 'desc',
private int $perPage = 25,
) {
//
}
public function __invoke(Builder $query): LengthAwarePaginator
{
return $query->orderBy($this->sortBy, $this->sortDirection)
->paginate($this->perPage, pageName: 'p');
}
}
使用查询构造器的 pipe() 方法,我们就可以利用这个对象来应用通用的分页逻辑:
$flights = DB::table('flights')
->tap(new DestinationFilter($destination))
->pipe(new Paginate);
调试
在构造查询时可以使用 dd() 和 dump() 方法输出当前的查询绑定与 SQL。dd() 方法会输出调试信息并终止请求。dump() 方法则会输出调试信息,但允许请求继续执行:
DB::table('users')->where('votes', '>', 100)->dd();
DB::table('users')->where('votes', '>', 100)->dump();
在查询上还可以调用 dumpRawSql() 和 ddRawSql() 方法,输出替换好所有参数绑定后的完整 SQL:
DB::table('users')->where('votes', '>', 100)->dumpRawSql();
DB::table('users')->where('votes', '>', 100)->ddRawSql();