跳转至内容

数据库:查询构建器

简介

Laravel 的数据库查询构建器提供了一个方便、流畅的接口,用于创建和执行数据库查询。它可用于执行应用程序中的大多数数据库操作,并与 Laravel 支持的所有数据库系统完美协作。

Laravel 查询构建器使用 PDO 参数绑定来保护您的应用程序免受 SQL 注入攻击。无需对作为查询绑定传递给查询构建器的字符串进行清理或转义。

PDO 不支持绑定列名。因此,您永远不应该允许用户输入来指定查询中引用的列名,包括 "order by" 列。

执行数据库查询

从表中检索所有行

您可以使用 DB 门面提供的 table 方法开始查询。table 方法返回一个针对给定表的流畅查询构建器实例,允许您在查询上链接更多约束,最后使用 get 方法检索查询结果。

1<?php
2 
3namespace App\Http\Controllers;
4 
5use Illuminate\Support\Facades\DB;
6use Illuminate\View\View;
7 
8class UserController extends Controller
9{
10 /**
11 * Show a list of all of the application's users.
12 */
13 public function index(): View
14 {
15 $users = DB::table('users')->get();
16 
17 return view('user.index', ['users' => $users]);
18 }
19}

get 方法返回一个 Illuminate\Support\Collection 实例,其中包含查询结果,每个结果都是 PHP stdClass 对象的一个实例。您可以通过将列作为对象的属性来访问每个列的值。

1use Illuminate\Support\Facades\DB;
2 
3$users = DB::table('users')->get();
4 
5foreach ($users as $user) {
6 echo $user->name;
7}

Laravel 集合提供了多种非常强大的方法来映射和缩减数据。有关 Laravel 集合的更多信息,请查看集合文档

从表中检索单行/单列

如果您只需要从数据库表中检索一行,可以使用 DB 门面的 first 方法。此方法将返回一个 stdClass 对象。

1$user = DB::table('users')->where('name', 'John')->first();
2 
3return $user->email;

如果您想从数据库表中检索一行,但如果未找到匹配行则抛出 Illuminate\Database\RecordNotFoundException 异常,可以使用 firstOrFail 方法。如果 RecordNotFoundException 未被捕获,将自动向客户端发送 404 HTTP 响应。

1$user = DB::table('users')->where('name', 'John')->firstOrFail();

如果您不需要整行数据,可以使用 value 方法从记录中提取单个值。此方法将直接返回该列的值。

1$email = DB::table('users')->where('name', 'John')->value('email');

要通过 id 列值检索单行,请使用 find 方法。

1$user = DB::table('users')->find(3);

检索列值列表

如果您想检索一个包含单列值的 Illuminate\Support\Collection 实例,可以使用 pluck 方法。在此示例中,我们将检索用户标题的集合。

1use Illuminate\Support\Facades\DB;
2 
3$titles = DB::table('users')->pluck('title');
4 
5foreach ($titles as $title) {
6 echo $title;
7}

您可以通过向 pluck 方法传递第二个参数,来指定生成的集合应使用哪一列作为其键。

1$titles = DB::table('users')->pluck('title', 'name');
2 
3foreach ($titles as $name => $title) {
4 echo $title;
5}

分块获取结果

如果您需要处理数千条数据库记录,请考虑使用 DB 门面提供的 chunk 方法。该方法一次检索一小块结果,并将每一块结果馈送到闭包中进行处理。例如,让我们以每次 100 条记录的分块方式检索整个 users 表。

1use Illuminate\Support\Collection;
2use Illuminate\Support\Facades\DB;
3 
4DB::table('users')->orderBy('id')->chunk(100, function (Collection $users) {
5 foreach ($users as $user) {
6 // ...
7 }
8});

您可以通过在闭包中返回 false 来停止后续分块的处理。

1DB::table('users')->orderBy('id')->chunk(100, function (Collection $users) {
2 // Process the records...
3 
4 return false;
5});

如果您在分块处理结果时更新数据库记录,分块结果可能会以意想不到的方式发生变化。如果您计划在分块时更新检索到的记录,最好改用 chunkById 方法。该方法将根据记录的主键自动对结果进行分页。

1DB::table('users')->where('active', false)
2 ->chunkById(100, function (Collection $users) {
3 foreach ($users as $user) {
4 DB::table('users')
5 ->where('id', $user->id)
6 ->update(['active' => true]);
7 }
8 });

由于 chunkByIdlazyById 方法会将它们自己的 "where" 条件添加到正在执行的查询中,因此您通常应该在闭包内逻辑地分组您自己的条件。

1DB::table('users')->where(function ($query) {
2 $query->where('credits', 1)->orWhere('credits', 2);
3})->chunkById(100, function (Collection $users) {
4 foreach ($users as $user) {
5 DB::table('users')
6 ->where('id', $user->id)
7 ->update(['credits' => 3]);
8 }
9});

在分块回调内更新或删除记录时,主键或外键的任何更改都可能影响分块查询。这可能会导致某些记录未被包含在分块结果中。

流式延迟获取结果

lazy 方法的工作方式类似于分块方法,因为它分块执行查询。但是,lazy() 方法不是将每一块传递给回调,而是返回一个 LazyCollection,让您可以将结果作为单一流进行交互。

1use Illuminate\Support\Facades\DB;
2 
3DB::table('users')->orderBy('id')->lazy()->each(function (object $user) {
4 // ...
5});

同样,如果您计划在迭代检索到的记录时更新它们,最好改用 lazyByIdlazyByIdDesc 方法。这些方法将根据记录的主键自动对结果进行分页。

1DB::table('users')->where('active', false)
2 ->lazyById()->each(function (object $user) {
3 DB::table('users')
4 ->where('id', $user->id)
5 ->update(['active' => true]);
6 });

在迭代期间更新或删除记录时,主键或外键的任何更改都可能影响分块查询。这可能会导致某些记录未被包含在结果中。

聚合函数

查询构建器还提供了各种用于检索聚合值的方法,如 countmaxminavgsum。您可以在构建查询后调用这些方法中的任何一个。

1use Illuminate\Support\Facades\DB;
2 
3$users = DB::table('users')->count();
4 
5$price = DB::table('orders')->max('price');

当然,您可以将这些方法与其他子句结合使用,以精细调整聚合值的计算方式。

1$price = DB::table('orders')
2 ->where('finalized', 1)
3 ->avg('price');

确定记录是否存在

除了使用 count 方法来确定是否存在符合查询约束的记录外,您还可以使用 existsdoesntExist 方法。

1if (DB::table('orders')->where('finalized', 1)->exists()) {
2 // ...
3}
4 
5if (DB::table('orders')->where('finalized', 1)->doesntExist()) {
6 // ...
7}

查询语句 (Select Statements)

指定 Select 子句

您可能并不总是希望从数据库表中选择所有列。使用 select 方法,您可以为查询指定自定义的 "select" 子句。

1use Illuminate\Support\Facades\DB;
2 
3$users = DB::table('users')
4 ->select('name', 'email as user_email')
5 ->get();

distinct 方法允许您强制查询返回不重复的结果。

1$users = DB::table('users')->distinct()->get();

如果您已经拥有一个查询构建器实例,并希望向其现有的 select 子句中添加列,可以使用 addSelect 方法。

1$query = DB::table('users')->select('name');
2 
3$users = $query->addSelect('age')->get();

原生表达式

有时您可能需要将任意字符串插入到查询中。要创建原生字符串表达式,可以使用 DB 门面提供的 raw 方法。

1$users = DB::table('users')
2 ->select(DB::raw('count(*) as user_count, status'))
3 ->where('status', '<>', 1)
4 ->groupBy('status')
5 ->get();

原生语句将作为字符串注入到查询中,因此您应该格外小心,以避免产生 SQL 注入漏洞。

原生方法

除了使用 DB::raw 方法外,您还可以使用以下方法将原生表达式插入到查询的不同部分。请记住,Laravel 无法保证任何使用原生表达式的查询都能免受 SQL 注入漏洞的影响。

selectRaw

selectRaw 方法可以代替 addSelect(DB::raw(/* ... */)) 使用。此方法接受一个可选的绑定数组作为其第二个参数。

1$orders = DB::table('orders')
2 ->selectRaw('price * ? as price_with_tax', [1.0825])
3 ->get();

whereRaw / orWhereRaw

whereRaworWhereRaw 方法可用于将原生 "where" 子句注入到查询中。这些方法接受一个可选的绑定数组作为其第二个参数。

1$orders = DB::table('orders')
2 ->whereRaw('price > IF(state = "TX", ?, 100)', [200])
3 ->get();

havingRaw / orHavingRaw

havingRaworHavingRaw 方法可用于提供原生字符串作为 "having" 子句的值。这些方法接受一个可选的绑定数组作为其第二个参数。

1$orders = DB::table('orders')
2 ->select('department', DB::raw('SUM(price) as total_sales'))
3 ->groupBy('department')
4 ->havingRaw('SUM(price) > ?', [2500])
5 ->get();

orderByRaw

orderByRaw 方法可用于提供原生字符串作为 "order by" 子句的值。

1$orders = DB::table('orders')
2 ->orderByRaw('updated_at - created_at DESC')
3 ->get();

groupByRaw

groupByRaw 方法可用于提供原生字符串作为 "group by" 子句的值。

1$orders = DB::table('orders')
2 ->select('city', 'state')
3 ->groupByRaw('city, state')
4 ->get();

连接 (Joins)

Inner Join 子句

查询构建器也可以用于向查询添加连接子句。要执行基础的 "inner join",您可以在查询构建器实例上使用 join 方法。传递给 join 方法的第一个参数是您需要连接的表名,而其余参数指定连接的列约束。您甚至可以在单个查询中连接多个表。

1use Illuminate\Support\Facades\DB;
2 
3$users = DB::table('users')
4 ->join('contacts', 'users.id', '=', 'contacts.user_id')
5 ->join('orders', 'users.id', '=', 'orders.user_id')
6 ->select('users.*', 'contacts.phone', 'orders.price')
7 ->get();

Left Join / Right Join 子句

如果您想执行 "left join" 或 "right join" 而不是 "inner join",请使用 leftJoinrightJoin 方法。这些方法的签名与 join 方法相同。

1$users = DB::table('users')
2 ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
3 ->get();
4 
5$users = DB::table('users')
6 ->rightJoin('posts', 'users.id', '=', 'posts.user_id')
7 ->get();

Cross Join 子句

您可以使用 crossJoin 方法执行 "cross join"(交叉连接)。交叉连接在第一张表和连接表之间生成笛卡尔积。

1$sizes = DB::table('sizes')
2 ->crossJoin('colors')
3 ->get();

高级 Join 子句

您还可以指定更高级的连接子句。首先,将一个闭包作为第二个参数传递给 join 方法。该闭包将接收一个 Illuminate\Database\Query\JoinClause 实例,允许您指定 "join" 子句的约束。

1DB::table('users')
2 ->join('contacts', function (JoinClause $join) {
3 $join->on('users.id', '=', 'contacts.user_id')->orOn(/* ... */);
4 })
5 ->get();

如果您想在连接上使用 "where" 子句,可以使用 JoinClause 实例提供的 whereorWhere 方法。这些方法不是比较两个列,而是将列与值进行比较。

1DB::table('users')
2 ->join('contacts', function (JoinClause $join) {
3 $join->on('users.id', '=', 'contacts.user_id')
4 ->where('contacts.user_id', '>', 5);
5 })
6 ->get();

子查询 Joins

您可以使用 joinSubleftJoinSubrightJoinSub 方法将查询连接到子查询。这些方法中的每一个都接收三个参数:子查询、其表别名以及一个定义关联列的闭包。在此示例中,我们将检索用户集合,其中每个用户记录还包含用户最近发布的博客文章的 created_at 时间戳。

1$latestPosts = DB::table('posts')
2 ->select('user_id', DB::raw('MAX(created_at) as last_post_created_at'))
3 ->where('is_published', true)
4 ->groupBy('user_id');
5 
6$users = DB::table('users')
7 ->joinSub($latestPosts, 'latest_posts', function (JoinClause $join) {
8 $join->on('users.id', '=', 'latest_posts.user_id');
9 })->get();

Lateral Joins

Lateral joins 目前受 PostgreSQL、MySQL >= 8.0.14 和 SQL Server 支持。

您可以使用 joinLateralleftJoinLateral 方法对子查询执行 "lateral join"。这些方法中的每一个都接收两个参数:子查询及其表别名。连接条件应在给定子查询的 where 子句中指定。Lateral joins 为每一行进行计算,并且可以引用子查询外部的列。

在此示例中,我们将检索用户集合以及用户最近的三篇博客文章。每个用户在结果集中最多产生三行:每行对应其最近的一篇博客文章。连接条件在子查询中使用 whereColumn 子句指定,引用当前用户行。

1$latestPosts = DB::table('posts')
2 ->select('id as post_id', 'title as post_title', 'created_at as post_created_at')
3 ->whereColumn('user_id', 'users.id')
4 ->orderBy('created_at', 'desc')
5 ->limit(3);
6 
7$users = DB::table('users')
8 ->joinLateral($latestPosts, 'latest_posts')
9 ->get();

联合查询 (Unions)

查询构建器还提供了一种方便的方法来将两个或多个查询 "union" 在一起。例如,您可以创建一个初始查询,并使用 union 方法将其与其他查询联合起来。

1use Illuminate\Support\Facades\DB;
2 
3$usersWithoutFirstName = DB::table('users')
4 ->whereNull('first_name');
5 
6$users = DB::table('users')
7 ->whereNull('last_name')
8 ->union($usersWithoutFirstName)
9 ->get();

除了 union 方法外,查询构建器还提供了 unionAll 方法。使用 unionAll 方法合并的查询不会删除重复结果。unionAll 方法的方法签名与 union 方法相同。

基础 Where 子句

Where 子句

您可以使用查询构建器的 where 方法将 "where" 子句添加到查询中。对 where 方法最基本的调用需要三个参数。第一个参数是列名。第二个参数是运算符,可以是数据库支持的任何运算符。第三个参数是与列值进行比较的值。

例如,以下查询检索 votes 列值等于 100age 列值大于 35 的用户。

1$users = DB::table('users')
2 ->where('votes', '=', 100)
3 ->where('age', '>', 35)
4 ->get();

为方便起见,如果您想验证某一列 = 给定值,可以将该值作为第二个参数传递给 where 方法。Laravel 将假定您希望使用 = 运算符。

1$users = DB::table('users')->where('votes', 100)->get();

您还可以向 where 方法提供关联数组,以快速查询多个列。

1$users = DB::table('users')->where([
2 'first_name' => 'Jane',
3 'last_name' => 'Doe',
4])->get();

如前所述,您可以使用您的数据库系统支持的任何运算符。

1$users = DB::table('users')
2 ->where('votes', '>=', 100)
3 ->get();
4 
5$users = DB::table('users')
6 ->where('votes', '<>', 100)
7 ->get();
8 
9$users = DB::table('users')
10 ->where('name', 'like', 'T%')
11 ->get();

您还可以将条件数组传递给 where 函数。数组的每个元素都应是一个数组,其中包含通常传递给 where 方法的三个参数。

1$users = DB::table('users')->where([
2 ['status', '=', '1'],
3 ['subscribed', '<>', '1'],
4])->get();

PDO 不支持绑定列名。因此,您永远不应该允许用户输入来指定查询中引用的列名,包括 "order by" 列。

MySQL 和 MariaDB 会在字符串与数字比较中自动将字符串类型转换为整数。在此过程中,非数字字符串会被转换为 0,这可能导致意想不到的结果。例如,如果您的表有一个值为 aaasecret 列,并且您运行 User::where('secret', 0),该行将被返回。为避免这种情况,请确保在查询中使用值之前,所有值都已强制转换为其适当的类型。

Or Where 子句

在链接调用查询构建器的 where 方法时,"where" 子句将使用 and 运算符连接在一起。但是,您可以使用 orWhere 方法使用 or 运算符将子句连接到查询。orWhere 方法接受与 where 方法相同的参数。

1$users = DB::table('users')
2 ->where('votes', '>', 100)
3 ->orWhere('name', 'John')
4 ->get();

如果您需要将 "or" 条件分组在括号内,可以将闭包作为第一个参数传递给 orWhere 方法。

1use Illuminate\Database\Query\Builder;
2 
3$users = DB::table('users')
4 ->where('votes', '>', 100)
5 ->orWhere(function (Builder $query) {
6 $query->where('name', 'Abigail')
7 ->where('votes', '>', 50);
8 })
9 ->get();

上面的示例将生成以下 SQL:

1select * from users where votes > 100 or (name = 'Abigail' and votes > 50)

您应该始终对 orWhere 调用进行分组,以避免在应用全局作用域时出现意外行为。

Where Not 子句

whereNotorWhereNot 方法可用于否定给定的查询约束组。例如,以下查询排除了清仓商品或价格低于 10 的商品。

1$products = DB::table('products')
2 ->whereNot(function (Builder $query) {
3 $query->where('clearance', true)
4 ->orWhere('price', '<', 10);
5 })
6 ->get();

Where Any / All / None 子句

有时您可能需要将相同的查询约束应用于多个列。例如,您可能希望检索任何给定列列表中 LIKE 给定值的所有记录。您可以使用 whereAny 方法实现此目的。

1$users = DB::table('users')
2 ->where('active', true)
3 ->whereAny([
4 'name',
5 'email',
6 'phone',
7 ], 'like', 'Example%')
8 ->get();

上面的查询将导致以下 SQL:

1SELECT *
2FROM users
3WHERE active = true AND (
4 name LIKE 'Example%' OR
5 email LIKE 'Example%' OR
6 phone LIKE 'Example%'
7)

同样,whereAll 方法可用于检索所有给定列都匹配给定约束的记录。

1$posts = DB::table('posts')
2 ->where('published', true)
3 ->whereAll([
4 'title',
5 'content',
6 ], 'like', '%Laravel%')
7 ->get();

上面的查询将导致以下 SQL:

1SELECT *
2FROM posts
3WHERE published = true AND (
4 title LIKE '%Laravel%' AND
5 content LIKE '%Laravel%'
6)

whereNone 方法可用于检索没有任何给定列匹配给定约束的记录。

1$albums = DB::table('albums')
2 ->where('published', true)
3 ->whereNone([
4 'title',
5 'lyrics',
6 'tags',
7 ], 'like', '%explicit%')
8 ->get();

上面的查询将导致以下 SQL:

1SELECT *
2FROM albums
3WHERE published = true AND NOT (
4 title LIKE '%explicit%' OR
5 lyrics LIKE '%explicit%' OR
6 tags LIKE '%explicit%'
7)

JSON Where 子句

Laravel 还支持在提供 JSON 列类型支持的数据库上查询 JSON 列类型。目前,这包括 MariaDB 10.3+、MySQL 8.0+、PostgreSQL 12.0+、SQL Server 2017+ 和 SQLite 3.39.0+。要查询 JSON 列,请使用 -> 运算符。

1$users = DB::table('users')
2 ->where('preferences->dining->meal', 'salad')
3 ->get();
4 
5$users = DB::table('users')
6 ->whereIn('preferences->dining->meal', ['pasta', 'salad', 'sandwiches'])
7 ->get();

您可以使用 whereJsonContainswhereJsonDoesntContain 方法来查询 JSON 数组。

1$users = DB::table('users')
2 ->whereJsonContains('options->languages', 'en')
3 ->get();
4 
5$users = DB::table('users')
6 ->whereJsonDoesntContain('options->languages', 'en')
7 ->get();

如果您的应用程序使用 MariaDB、MySQL 或 PostgreSQL 数据库,您可以将值数组传递给 whereJsonContainswhereJsonDoesntContain 方法。

1$users = DB::table('users')
2 ->whereJsonContains('options->languages', ['en', 'de'])
3 ->get();
4 
5$users = DB::table('users')
6 ->whereJsonDoesntContain('options->languages', ['en', 'de'])
7 ->get();

此外,您可以使用 whereJsonContainsKeywhereJsonDoesntContainKey 方法来检索包含或不包含 JSON 键的结果。

1$users = DB::table('users')
2 ->whereJsonContainsKey('preferences->dietary_requirements')
3 ->get();
4 
5$users = DB::table('users')
6 ->whereJsonDoesntContainKey('preferences->dietary_requirements')
7 ->get();

最后,您可以使用 whereJsonLength 方法根据长度查询 JSON 数组。

1$users = DB::table('users')
2 ->whereJsonLength('options->languages', 0)
3 ->get();
4 
5$users = DB::table('users')
6 ->whereJsonLength('options->languages', '>', 1)
7 ->get();

附加 Where 子句

whereLike / orWhereLike / whereNotLike / orWhereNotLike

whereLike 方法允许您向查询添加 "LIKE" 子句进行模式匹配。这些方法提供了一种数据库无关的方式来执行字符串匹配查询,并能够切换大小写敏感性。默认情况下,字符串匹配是不区分大小写的。

1$users = DB::table('users')
2 ->whereLike('name', '%John%')
3 ->get();

您可以通过 caseSensitive 参数启用区分大小写的搜索。

1$users = DB::table('users')
2 ->whereLike('name', '%John%', caseSensitive: true)
3 ->get();

orWhereLike 方法允许您添加带有 LIKE 条件的 "or" 子句。

1$users = DB::table('users')
2 ->where('votes', '>', 100)
3 ->orWhereLike('name', '%John%')
4 ->get();

whereNotLike 方法允许您向查询添加 "NOT LIKE" 子句。

1$users = DB::table('users')
2 ->whereNotLike('name', '%John%')
3 ->get();

同样,您可以使用 orWhereNotLike 添加带有 NOT LIKE 条件的 "or" 子句。

1$users = DB::table('users')
2 ->where('votes', '>', 100)
3 ->orWhereNotLike('name', '%John%')
4 ->get();

SQL Server 目前不支持 whereLike 的大小写敏感搜索选项。

whereIn / whereNotIn / orWhereIn / orWhereNotIn

whereIn 方法验证给定列的值是否包含在给定数组中。

1$users = DB::table('users')
2 ->whereIn('id', [1, 2, 3])
3 ->get();

whereNotIn 方法验证给定列的值是否不包含在给定数组中。

1$users = DB::table('users')
2 ->whereNotIn('id', [1, 2, 3])
3 ->get();

您还可以将查询对象作为 whereIn 方法的第二个参数提供。

1$activeUsers = DB::table('users')->select('id')->where('is_active', 1);
2 
3$comments = DB::table('comments')
4 ->whereIn('user_id', $activeUsers)
5 ->get();

上面的示例将生成以下 SQL:

1select * from comments where user_id in (
2 select id
3 from users
4 where is_active = 1
5)

如果您正在向查询添加大量的整数绑定数组,可以使用 whereIntegerInRawwhereIntegerNotInRaw 方法,以大大减少内存使用量。

whereBetween / orWhereBetween

whereBetween 方法验证列的值是否在两个值之间。

1$users = DB::table('users')
2 ->whereBetween('votes', [1, 100])
3 ->get();

whereNotBetween / orWhereNotBetween

whereNotBetween 方法验证列的值是否在两个值之外。

1$users = DB::table('users')
2 ->whereNotBetween('votes', [1, 100])
3 ->get();

whereBetweenColumns / whereNotBetweenColumns / orWhereBetweenColumns / orWhereNotBetweenColumns

whereBetweenColumns 方法验证列的值是否在同一表行中两列的两个值之间。

1$patients = DB::table('patients')
2 ->whereBetweenColumns('weight', ['minimum_allowed_weight', 'maximum_allowed_weight'])
3 ->get();

whereNotBetweenColumns 方法验证列的值是否在同一表行中两列的两个值之外。

1$patients = DB::table('patients')
2 ->whereNotBetweenColumns('weight', ['minimum_allowed_weight', 'maximum_allowed_weight'])
3 ->get();

whereValueBetween / whereValueNotBetween / orWhereValueBetween / orWhereValueNotBetween

whereValueBetween 方法验证给定值是否在同一表行中两列相同类型的两个值之间。

1$products = DB::table('products')
2 ->whereValueBetween(100, ['min_price', 'max_price'])
3 ->get();

whereValueNotBetween 方法验证一个值是否在同一表行中两列的两个值之外。

1$products = DB::table('products')
2 ->whereValueNotBetween(100, ['min_price', 'max_price'])
3 ->get();

whereNull / whereNotNull / orWhereNull / orWhereNotNull

whereNull 方法验证给定列的值是否为 NULL

1$users = DB::table('users')
2 ->whereNull('updated_at')
3 ->get();

whereNotNull 方法验证列的值是否不为 NULL

1$users = DB::table('users')
2 ->whereNotNull('updated_at')
3 ->get();

whereDate / whereMonth / whereDay / whereYear / whereTime

whereDate 方法可用于将列的值与日期进行比较。

1$users = DB::table('users')
2 ->whereDate('created_at', '2016-12-31')
3 ->get();

whereMonth 方法可用于将列的值与特定月份进行比较。

1$users = DB::table('users')
2 ->whereMonth('created_at', '12')
3 ->get();

whereDay 方法可用于将列的值与特定日期进行比较。

1$users = DB::table('users')
2 ->whereDay('created_at', '31')
3 ->get();

whereYear 方法可用于将列的值与特定年份进行比较。

1$users = DB::table('users')
2 ->whereYear('created_at', '2016')
3 ->get();

whereTime 方法可用于将列的值与特定时间进行比较。

1$users = DB::table('users')
2 ->whereTime('created_at', '=', '11:20:45')
3 ->get();

wherePast / whereFuture / whereToday / whereBeforeToday / whereAfterToday

wherePastwhereFuture 方法可用于确定列的值是在过去还是未来。

1$invoices = DB::table('invoices')
2 ->wherePast('due_at')
3 ->get();
4 
5$invoices = DB::table('invoices')
6 ->whereFuture('due_at')
7 ->get();

whereNowOrPastwhereNowOrFuture 方法可用于确定列的值是在过去还是未来(包含当前日期和时间)。

1$invoices = DB::table('invoices')
2 ->whereNowOrPast('due_at')
3 ->get();
4 
5$invoices = DB::table('invoices')
6 ->whereNowOrFuture('due_at')
7 ->get();

whereTodaywhereBeforeTodaywhereAfterToday 方法分别可用于确定列的值是否为今天、今天之前或今天之后。

1$invoices = DB::table('invoices')
2 ->whereToday('due_at')
3 ->get();
4 
5$invoices = DB::table('invoices')
6 ->whereBeforeToday('due_at')
7 ->get();
8 
9$invoices = DB::table('invoices')
10 ->whereAfterToday('due_at')
11 ->get();

同样,whereTodayOrBeforewhereTodayOrAfter 方法可用于确定列的值是否在今天之前或今天之后(包含今天日期)。

1$invoices = DB::table('invoices')
2 ->whereTodayOrBefore('due_at')
3 ->get();
4 
5$invoices = DB::table('invoices')
6 ->whereTodayOrAfter('due_at')
7 ->get();

whereColumn / orWhereColumn

whereColumn 方法可用于验证两列是否相等。

1$users = DB::table('users')
2 ->whereColumn('first_name', 'last_name')
3 ->get();

您还可以将比较运算符传递给 whereColumn 方法。

1$users = DB::table('users')
2 ->whereColumn('updated_at', '>', 'created_at')
3 ->get();

您还可以将列比较数组传递给 whereColumn 方法。这些条件将使用 and 运算符连接。

1$users = DB::table('users')
2 ->whereColumn([
3 ['first_name', '=', 'last_name'],
4 ['updated_at', '>', 'created_at'],
5 ])->get();

逻辑分组

有时您可能需要将多个 "where" 子句分组在括号内,以实现查询所需的逻辑分组。实际上,您通常应该始终在括号中对 orWhere 方法的调用进行分组,以避免意外的查询行为。要实现这一点,您可以将闭包传递给 where 方法。

1$users = DB::table('users')
2 ->where('name', '=', 'John')
3 ->where(function (Builder $query) {
4 $query->where('votes', '>', 100)
5 ->orWhere('title', '=', 'Admin');
6 })
7 ->get();

如您所见,将闭包传递给 where 方法指示查询构建器开始一个约束组。该闭包将接收一个查询构建器实例,您可以使用该实例设置应包含在括号组中的约束。上面的示例将生成以下 SQL:

1select * from users where name = 'John' and (votes > 100 or title = 'Admin')

您应该始终对 orWhere 调用进行分组,以避免在应用全局作用域时出现意外行为。

高级 Where 子句

Where Exists 子句

whereExists 方法允许您编写 "where exists" SQL 子句。whereExists 方法接受一个闭包,该闭包将接收一个查询构建器实例,允许您定义应放置在 "exists" 子句内的查询。

1$users = DB::table('users')
2 ->whereExists(function (Builder $query) {
3 $query->select(DB::raw(1))
4 ->from('orders')
5 ->whereColumn('orders.user_id', 'users.id');
6 })
7 ->get();

或者,您可以向 whereExists 方法提供查询对象,而不是闭包。

1$orders = DB::table('orders')
2 ->select(DB::raw(1))
3 ->whereColumn('orders.user_id', 'users.id');
4 
5$users = DB::table('users')
6 ->whereExists($orders)
7 ->get();

以上两个示例都将生成以下 SQL:

1select * from users
2where exists (
3 select 1
4 from orders
5 where orders.user_id = users.id
6)

子查询 Where 子句

有时您可能需要构造一个将子查询结果与给定值进行比较的 "where" 子句。您可以通过将闭包和值传递给 where 方法来实现。例如,以下查询将检索所有拥有给定类型最近 "membership" 的用户:

1use App\Models\User;
2use Illuminate\Database\Query\Builder;
3 
4$users = User::where(function (Builder $query) {
5 $query->select('type')
6 ->from('membership')
7 ->whereColumn('membership.user_id', 'users.id')
8 ->orderByDesc('membership.start_date')
9 ->limit(1);
10}, 'Pro')->get();

或者,您可能需要构造一个将列与子查询结果进行比较的 "where" 子句。您可以通过将列、运算符和闭包传递给 where 方法来实现。例如,以下查询将检索所有金额小于平均值的收入记录:

1use App\Models\Income;
2use Illuminate\Database\Query\Builder;
3 
4$incomes = Income::where('amount', '<', function (Builder $query) {
5 $query->selectRaw('avg(i.amount)')->from('incomes as i');
6})->get();

全文搜索 Where 子句

全文搜索 Where 子句目前受 MariaDB、MySQL 和 PostgreSQL 支持。

whereFullTextorWhereFullText 方法可用于为具有全文索引的列向查询添加全文 "where" 子句。这些方法将被 Laravel 转换为底层数据库系统所需的适当 SQL。例如,将为使用 MariaDB 或 MySQL 的应用程序生成 MATCH AGAINST 子句。

1$users = DB::table('users')
2 ->whereFullText('bio', 'web developer')
3 ->get();

向量相似度子句

向量相似度子句目前仅在使用 pgvector 扩展的 PostgreSQL 连接上受支持。有关定义向量列和索引的信息,请咨询迁移文档

whereVectorSimilarTo 方法根据给定向量的余弦相似度过滤结果,并按相关性对结果进行排序。minSimilarity 阈值应为 0.01.0 之间的值,其中 1.0 表示完全相同。

1$documents = DB::table('documents')
2 ->whereVectorSimilarTo('embedding', $queryEmbedding, minSimilarity: 0.4)
3 ->limit(10)
4 ->get();

当纯字符串作为向量参数给出时,Laravel 将自动使用 Laravel AI SDK 为其生成嵌入。

1$documents = DB::table('documents')
2 ->whereVectorSimilarTo('embedding', 'Best wineries in Napa Valley')
3 ->limit(10)
4 ->get();

默认情况下,whereVectorSimilarTo 也会按距离对结果排序(最相似的优先)。您可以通过将 false 作为 order 参数传递来禁用此排序。

1$documents = DB::table('documents')
2 ->whereVectorSimilarTo('embedding', $queryEmbedding, minSimilarity: 0.4, order: false)
3 ->orderBy('created_at', 'desc')
4 ->limit(10)
5 ->get();

如果您需要更多控制,可以独立使用 selectVectorDistancewhereVectorDistanceLessThanorderByVectorDistance 方法。

1$documents = DB::table('documents')
2 ->select('*')
3 ->selectVectorDistance('embedding', $queryEmbedding, as: 'distance')
4 ->whereVectorDistanceLessThan('embedding', $queryEmbedding, maxDistance: 0.3)
5 ->orderByVectorDistance('embedding', $queryEmbedding)
6 ->limit(10)
7 ->get();

使用 PostgreSQL 时,必须先加载 pgvector 扩展,然后才能创建 vector 列。

1Schema::ensureVectorExtensionExists();

排序、分组、限制与偏移

排序

orderBy 方法

orderBy 方法允许您按给定列对查询结果进行排序。orderBy 方法接受的第一个参数应为您希望排序的列,而第二个参数决定排序方向,可以是 ascdesc

1$users = DB::table('users')
2 ->orderBy('name', 'desc')
3 ->get();

要按多列排序,只需根据需要多次调用 orderBy 即可。

1$users = DB::table('users')
2 ->orderBy('name', 'desc')
3 ->orderBy('email', 'asc')
4 ->get();

排序方向是可选的,默认为升序。如果您想按降序排序,可以为 orderBy 方法指定第二个参数,或者直接使用 orderByDesc

1$users = DB::table('users')
2 ->orderByDesc('verified_at')
3 ->get();

最后,使用 -> 运算符,可以按 JSON 列中的值对结果进行排序。

1$corporations = DB::table('corporations')
2 ->where('country', 'US')
3 ->orderBy('location->state')
4 ->get();

latestoldest 方法

latestoldest 方法允许您轻松地按日期对结果进行排序。默认情况下,结果将按表的 created_at 列进行排序。或者,您可以传递您希望排序的列名。

1$user = DB::table('users')
2 ->latest()
3 ->first();

随机排序

inRandomOrder 方法可用于随机对查询结果进行排序。例如,您可以使用此方法获取一个随机用户。

1$randomUser = DB::table('users')
2 ->inRandomOrder()
3 ->first();

移除现有排序

reorder 方法会移除之前已应用于查询的所有 "order by" 子句。

1$query = DB::table('users')->orderBy('name');
2 
3$unorderedUsers = $query->reorder()->get();

您可以在调用 reorder 方法时传递列和方向,以移除所有现有的 "order by" 子句并对查询应用全新的排序。

1$query = DB::table('users')->orderBy('name');
2 
3$usersOrderedByEmail = $query->reorder('email', 'desc')->get();

为方便起见,您可以使用 reorderDesc 方法以降序对查询结果重新排序。

1$query = DB::table('users')->orderBy('name');
2 
3$usersOrderedByEmail = $query->reorderDesc('email')->get();

分组

groupByhaving 方法

正如您所预料的,groupByhaving 方法可用于对查询结果进行分组。having 方法的签名类似于 where 方法。

1$users = DB::table('users')
2 ->groupBy('account_id')
3 ->having('account_id', '>', 100)
4 ->get();

您可以使用 havingBetween 方法来过滤给定范围内的结果。

1$report = DB::table('orders')
2 ->selectRaw('count(id) as number_of_orders, customer_id')
3 ->groupBy('customer_id')
4 ->havingBetween('number_of_orders', [5, 15])
5 ->get();

您可以将多个参数传递给 groupBy 方法以按多列分组。

1$users = DB::table('users')
2 ->groupBy('first_name', 'status')
3 ->having('account_id', '>', 100)
4 ->get();

要构建更高级的 having 语句,请参阅 havingRaw 方法。

限制与偏移

您可以使用 limitoffset 方法来限制从查询返回的结果数量,或跳过查询中的给定数量结果。

1$users = DB::table('users')
2 ->offset(10)
3 ->limit(5)
4 ->get();

条件子句

有时您可能希望根据另一个条件将特定的查询子句应用于查询。例如,您可能只想在传入的 HTTP 请求中存在给定的输入值时才应用 where 语句。您可以使用 when 方法实现此目的。

1$role = $request->input('role');
2 
3$users = DB::table('users')
4 ->when($role, function (Builder $query, string $role) {
5 $query->where('role_id', $role);
6 })
7 ->get();

when 方法仅在第一个参数为 true 时执行给定的闭包。如果第一个参数为 false,则不会执行该闭包。因此,在上面的示例中,提供给 when 方法的闭包仅在 role 字段出现在传入请求中且计算结果为 true 时才会被调用。

您可以将另一个闭包作为第三个参数传递给 when 方法。此闭包仅在第一个参数计算结果为 false 时执行。为了说明如何使用此功能,我们将使用它来配置查询的默认排序。

1$sortByVotes = $request->boolean('sort_by_votes');
2 
3$users = DB::table('users')
4 ->when($sortByVotes, function (Builder $query, bool $sortByVotes) {
5 $query->orderBy('votes');
6 }, function (Builder $query) {
7 $query->orderBy('name');
8 })
9 ->get();

插入语句

查询构建器还提供了一个 insert 方法,可用于向数据库表中插入记录。insert 方法接受列名和值的数组。

1DB::table('users')->insert([
2 'email' => '[email protected]',
3 'votes' => 0
4]);

您可以通过传递数组的数组来一次插入多条记录。每个数组代表应插入表中的一条记录。

1DB::table('users')->insert([
2 ['email' => '[email protected]', 'votes' => 0],
3 ['email' => '[email protected]', 'votes' => 0],
4]);

insertOrIgnore 方法将在向数据库插入记录时忽略错误。使用此方法时,请注意重复记录错误将被忽略,并且根据数据库引擎的不同,其他类型的错误也可能被忽略。例如,insertOrIgnore绕过 MySQL 的严格模式

1DB::table('users')->insertOrIgnore([
2 ['id' => 1, 'email' => '[email protected]'],
3 ['id' => 2, 'email' => '[email protected]'],
4]);

insertUsing 方法将在使用子查询确定应插入的数据的同时,向表中插入新记录。

1DB::table('pruned_users')->insertUsing([
2 'id', 'name', 'email', 'email_verified_at'
3], DB::table('users')->select(
4 'id', 'name', 'email', 'email_verified_at'
5)->where('updated_at', '<=', now()->minus(months: 1)));

自动递增 ID

如果表具有自动递增 ID,请使用 insertGetId 方法插入记录并检索该 ID。

1$id = DB::table('users')->insertGetId(
2 ['email' => '[email protected]', 'votes' => 0]
3);

使用 PostgreSQL 时,insertGetId 方法期望自动递增列被命名为 id。如果您想从不同的 "sequence" 中检索 ID,可以将列名作为第二个参数传递给 insertGetId 方法。

Upsert (更新或插入)

upsert 方法将插入不存在的记录,并使用您指定的新值更新已存在的记录。该方法的第一个参数由要插入或更新的值组成,第二个参数列出了在关联表中唯一标识记录的列。该方法的第三个(也是最后一个)参数是当数据库中已存在匹配记录时应更新的列数组。

1DB::table('flights')->upsert(
2 [
3 ['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99],
4 ['departure' => 'Chicago', 'destination' => 'New York', 'price' => 150]
5 ],
6 ['departure', 'destination'],
7 ['price']
8);

在上面的示例中,Laravel 将尝试插入两条记录。如果已存在具有相同 departuredestination 列值的记录,Laravel 将更新该记录的 price 列。

除 SQL Server 外,所有数据库都要求 upsert 方法第二个参数中的列具有 "primary" 或 "unique" 索引。此外,MariaDB 和 MySQL 数据库驱动程序会忽略 upsert 方法的第二个参数,并始终使用表的 "primary" 和 "unique" 索引来检测现有记录。

更新语句

除了向数据库插入记录外,查询构建器还可以使用 update 方法更新现有记录。与 insert 方法一样,update 方法接受列和值对的数组,指示要更新的列。update 方法返回受影响的行数。您可以使用 where 子句约束 update 查询。

1$affected = DB::table('users')
2 ->where('id', 1)
3 ->update(['votes' => 1]);

更新或插入

有时您可能希望更新数据库中的现有记录,如果不存在匹配记录,则创建它。在这种情况下,可以使用 updateOrInsert 方法。updateOrInsert 方法接受两个参数:用于查找记录的条件数组,以及指示要更新的列和值对的数组。

updateOrInsert 方法将尝试使用第一个参数的列和值对来定位匹配的数据库记录。如果记录存在,它将使用第二个参数中的值进行更新。如果找不到记录,将插入一条包含两个参数合并属性的新记录。

1DB::table('users')
2 ->updateOrInsert(
3 ['email' => '[email protected]', 'name' => 'John'],
4 ['votes' => '2']
5 );

您可以向 updateOrInsert 方法提供闭包,以根据是否存在匹配记录来自定义插入或更新到数据库中的属性。

1DB::table('users')->updateOrInsert(
2 ['user_id' => $user_id],
3 fn ($exists) => $exists ? [
4 'name' => $data['name'],
5 'email' => $data['email'],
6 ] : [
7 'name' => $data['name'],
8 'email' => $data['email'],
9 'marketable' => true,
10 ],
11);

更新 JSON 列

更新 JSON 列时,应使用 -> 语法来更新 JSON 对象中的相应键。此操作在 MariaDB 10.3+、MySQL 5.7+ 和 PostgreSQL 9.5+ 上受支持。

1$affected = DB::table('users')
2 ->where('id', 1)
3 ->update(['options->enabled' => true]);

递增与递减

查询构建器还提供了用于递增或递减给定列值的便捷方法。这两个方法至少接受一个参数:要修改的列。可以提供第二个参数来指定列应递增或递减的量。

1DB::table('users')->increment('votes');
2 
3DB::table('users')->increment('votes', 5);
4 
5DB::table('users')->decrement('votes');
6 
7DB::table('users')->decrement('votes', 5);

如果需要,您还可以在递增或递减操作期间指定要更新的其他列。

1DB::table('users')->increment('votes', 1, ['name' => 'John']);

此外,您可以使用 incrementEachdecrementEach 方法同时递增或递减多个列。

1DB::table('users')->incrementEach([
2 'votes' => 5,
3 'balance' => 100,
4]);

删除语句

查询构建器的 delete 方法可用于从表中删除记录。delete 方法返回受影响的行数。您可以在调用 delete 方法之前添加 "where" 子句来约束 delete 语句。

1$deleted = DB::table('users')->delete();
2 
3$deleted = DB::table('users')->where('votes', '>', 100)->delete();

悲观锁

查询构建器还包含一些函数,可帮助您在执行 select 语句时实现 "悲观锁"。要执行带有 "shared lock"(共享锁)的语句,您可以调用 sharedLock 方法。共享锁可防止选定行在您的事务提交之前被修改。

1DB::table('users')
2 ->where('votes', '>', 100)
3 ->sharedLock()
4 ->get();

或者,您可以使用 lockForUpdate 方法。"for update" 锁可防止选定记录被修改或被其他共享锁选中。

1DB::table('users')
2 ->where('votes', '>', 100)
3 ->lockForUpdate()
4 ->get();

虽然不是必须的,但建议在事务中包装悲观锁。这确保检索到的数据在整个操作完成之前在数据库中保持不变。如果发生故障,事务将回滚所有更改并自动释放锁。

1DB::transaction(function () {
2 $sender = DB::table('users')
3 ->lockForUpdate()
4 ->find(1);
5 
6 $receiver = DB::table('users')
7 ->lockForUpdate()
8 ->find(2);
9 
10 if ($sender->balance < 100) {
11 throw new RuntimeException('Balance too low.');
12 }
13 
14 DB::table('users')
15 ->where('id', $sender->id)
16 ->update([
17 'balance' => $sender->balance - 100
18 ]);
19 
20 DB::table('users')
21 ->where('id', $receiver->id)
22 ->update([
23 'balance' => $receiver->balance + 100
24 ]);
25});

可复用的查询组件

如果您在整个应用程序中重复查询逻辑,可以使用查询构建器的 tappipe 方法将逻辑提取到可重用的对象中。想象一下您在应用程序中有这两个不同的查询:

1use Illuminate\Database\Query\Builder;
2use Illuminate\Support\Facades\DB;
3 
4$destination = $request->query('destination');
5 
6DB::table('flights')
7 ->when($destination, function (Builder $query, string $destination) {
8 $query->where('destination', $destination);
9 })
10 ->orderByDesc('price')
11 ->get();
12 
13// ...
14 
15$destination = $request->query('destination');
16 
17DB::table('flights')
18 ->when($destination, function (Builder $query, string $destination) {
19 $query->where('destination', $destination);
20 })
21 ->where('user', $request->user()->id)
22 ->orderBy('destination')
23 ->get();

您可能希望将查询之间通用的目标过滤提取到可重用的对象中:

1<?php
2 
3namespace App\Scopes;
4 
5use Illuminate\Database\Query\Builder;
6 
7class DestinationFilter
8{
9 public function __construct(
10 private ?string $destination,
11 ) {
12 //
13 }
14 
15 public function __invoke(Builder $query): void
16 {
17 $query->when($this->destination, function (Builder $query) {
18 $query->where('destination', $this->destination);
19 });
20 }
21}

然后,您可以使用查询构建器的 tap 方法将对象的逻辑应用于查询:

1use App\Scopes\DestinationFilter;
2use Illuminate\Database\Query\Builder;
3use Illuminate\Support\Facades\DB;
4 
5DB::table('flights')
6 ->when($destination, function (Builder $query, string $destination) {
7 $query->where('destination', $destination);
8 })
9 ->tap(new DestinationFilter($destination))
10 ->orderByDesc('price')
11 ->get();
12 
13// ...
14 
15DB::table('flights')
16 ->when($destination, function (Builder $query, string $destination) {
17 $query->where('destination', $destination);
18 })
19 ->tap(new DestinationFilter($destination))
20 ->where('user', $request->user()->id)
21 ->orderBy('destination')
22 ->get();

查询管道 (Query Pipes)

tap 方法将始终返回查询构建器。如果您想提取一个执行查询并返回其他值的对象,则可以使用 pipe 方法。

考虑以下查询对象,其中包含在整个应用程序中使用的共享分页逻辑。与将查询条件应用于查询的 DestinationFilter 不同,Paginate 对象执行查询并返回分页器实例:

1<?php
2 
3namespace App\Scopes;
4 
5use Illuminate\Contracts\Pagination\LengthAwarePaginator;
6use Illuminate\Database\Query\Builder;
7 
8class Paginate
9{
10 public function __construct(
11 private string $sortBy = 'timestamp',
12 private string $sortDirection = 'desc',
13 private int $perPage = 25,
14 ) {
15 //
16 }
17 
18 public function __invoke(Builder $query): LengthAwarePaginator
19 {
20 return $query->orderBy($this->sortBy, $this->sortDirection)
21 ->paginate($this->perPage, pageName: 'p');
22 }
23}

使用查询构建器的 pipe 方法,我们可以利用此对象来应用我们的共享分页逻辑:

1$flights = DB::table('flights')
2 ->tap(new DestinationFilter($destination))
3 ->pipe(new Paginate);

调试

您可以在构建查询时使用 dddump 方法来输出当前查询绑定和 SQL。dd 方法将显示调试信息,然后停止执行请求。dump 方法将显示调试信息,但允许请求继续执行。

1DB::table('users')->where('votes', '>', 100)->dd();
2 
3DB::table('users')->where('votes', '>', 100)->dump();

dumpRawSqlddRawSql 方法可以在查询上调用,以输出已正确替换所有参数绑定的查询 SQL。

1DB::table('users')->where('votes', '>', 100)->dumpRawSql();
2 
3DB::table('users')->where('votes', '>', 100)->ddRawSql();