Laravel 的数据库查询构建器提供了一个方便、流畅的接口,用于创建和运行数据库查询。它可用于在你的应用程序中执行大多数数据库操作并与 Laravel 支持的所有数据库系统完美配合。
Laravel 查询构建器使用 PDO 参数绑定来保护你的应用免受 SQL 注入攻击。无需清理或净化作为查询绑定传递给查询构建器的字符串。
[!WARNING]
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;
}[!NOTE]
Laravel 集合提供了各种极其强大的方法,用于映射和归约数据。 有关 Laravel 集合的更多信息,请查阅 集合文档。
如果您只需要从数据库表中检索单行数据,您可以使用 DB facade 的 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 方法。在此示例中,我们将获取用户标题的集合:
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 facade 提供的 chunk 方法。此方法每次检索一小块结果,并将每块结果馈送给一个闭包进行处理。例如,让我们以每次 100 条记录的方式检索整个 users 表:
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 方法,因为它会分块执行查询。然而,不是将每个块传递给回调函数,lazy() 方法而是返回一个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]);
});[!WARNING]
在迭代记录时更新或删除记录时,对主键或外键的任何更改都可能会影响分块查询。这可能会导致记录未包含在结果中。
查询构建器也提供了各种方法用于检索聚合值例如 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”子句:
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 facade 提供的 raw 方法:
$users = DB::table('users')
->select(DB::raw('count(*) as user_count, status'))
->where('status', `<>`, 1)
->groupBy('status')
->get();[!WARNING]
原始语句将作为字符串注入到查询中,因此您务必谨慎,以避免创建 SQL 注入漏洞。
除了使用 DB::raw 方法外,您还可以使用以下方法将原始表达式插入到查询的各个部分。 请记住,Laravel 无法保证任何使用原始表达式的查询都能够防止 SQL 注入漏洞。
选择原始该 selectRaw 方法 可以用来替代 addSelect(DB::raw(/* ... */))。 该 方法 接受 一个可选的绑定数组 作为其第二个参数:
$orders = DB::table('orders')
->selectRaw('price * ? as price_with_tax', [1.0825])
->get();whereRaw 或 orWhereRawwhereRaw 和 orWhereRaw 方法可用于将原始的 "where" 子句注入到您的查询中. 这些方法接受一个可选的绑定数组作为它们的第二个参数:
$orders = DB::table('orders')
->whereRaw('price > IF(state = "TX", ?, 100)', [200])
->get();having原生 / orHaving原生havingRaw 和 orHavingRaw 方法可用于提供一个原始字符串作为 "having" 子句的值。这些方法接受一个可选的绑定数组作为它们的第二个参数:
$orders = DB::table('orders')
->select('department', DB::raw('SUM(price) as total_sales'))
->groupBy('department')
->havingRaw('SUM(price) > ?', [2500])
->get();原始排序orderByRaw 方法可用于提供一个原始字符串作为 "order by" 子句的值:
$orders = DB::table('orders')
->orderByRaw('updated_at - created_at DESC')
->get();原生分组groupByRaw 方法可用于提供原始字符串作为 group by 子句的值:
$orders = DB::table('orders')
->select('city', 'state')
->groupByRaw('city, state')
->get();查询构建器也可用于向查询添加连接子句。要执行基本的“内部连接”,您可以在查询构建器实例上使用 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 方法。该闭包将接收一个 Illuminate\Database\Query\JoinClause 实例,它允许你指定在“连接”子句上的约束:
DB::table('users')
->join('contacts', function (JoinClause $join) {
$join->on('users.id', '=', 'contacts.user_id')->orOn(/* ... */);
})
->get();如果你想在你的连接上使用一个“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();您可以使用 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();[!WARNING]
侧向联接目前由 PostgreSQL、MySQL >= 8.0.14 和 SQL Server 支持。
您可以使用 joinLateral 和 leftJoinLateral 方法来执行与子查询的“横向连接”。这些方法中的每一个都接收两个参数:子查询和它的表别名。连接条件应在给定子查询的 where 子句中指定。横向连接对每一行进行评估,并且可以引用子查询之外的列。
在此示例中,我们将检索用户集合以及用户的三篇最新博客文章。每个用户在结果集中最多可生成三行:每行对应他们的一篇最新博客文章。连接条件通过 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 方法将其与更多查询联合:
use Illuminate\Support\Facades\DB;
$first = DB::table('users')
->whereNull('first_name');
$users = DB::table('users')
->whereNull('last_name')
->union($first)
->get();除了 union 方法之外,查询构建器还提供了一个 unionAll 方法。使用 unionAll 方法组合的查询将不会移除重复结果。unionAll 方法与 union 方法具有相同的方法签名。
您可以使用查询构造器的 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),则该行将被返回。为避免此问题,请确保所有值在查询中使用之前都已转换为其适当的类型。
当链式调用查询构建器的 where 方法时,这些“where”子句将使用 and 操作符连接起来。但是,你可以使用 orWhere 方法,通过 or 操作符将子句连接到查询中。orWhere 方法接受与 where 方法相同的参数:
$users = DB::table('users')
->where('votes', `>`, 100)
->orWhere('name', 'John')
->get();如果你需要将“或”条件用括号分组,你可以将闭包作为第一个参数传递给 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)[!WARNING]
你应该始终将orWhere调用分组,以避免在应用全局作用域时出现意外行为。
whereNot 和 orWhereNot 方法可用于否定给定组的查询约束。例如,以下查询排除了正在清仓或价格低于十的产品:
$products = DB::table('products')
->whereNot(function (Builder $query) {
$query->where('clearance', true)
->orWhere('price', `<`, 10);
})
->get();有时您可能需要对多个列应用相同的查询约束。例如,您可能希望检索所有记录,其中给定列表中的任何列都 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 方法可用于检索记录,其中给定列中的任意一列均不匹配给定约束:
$posts = 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%'
)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();条件匹配 / 或条件匹配 / 条件不匹配 / 或条件不匹配
该 whereLike 方法允许你为查询添加“LIKE”子句以进行模式匹配。这些方法提供了一种与数据库无关的方式来执行字符串匹配查询,并能够切换大小写敏感性。默认情况下,字符串匹配不区分大小写:
$users = DB::table('users')
->whereLike('name', '%John%')
->get();你可以通过 caseSensitive 参数启用区分大小写的搜索:
$users = DB::table('users')
->whereLike('name', '%John%', caseSensitive: true)
->get();orWhereLike 方法允许你添加一个带有 LIKE 条件的“或”子句:
$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();[!WARNING]
whereLike区分大小写的搜索选项目前在 SQL Server 上不受支持。
在其中 / 不在其中 / 或在其中 / 或不在其中
该 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);
$users = 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 方法验证某个列的值介于两个值之间:
$users = DB::table('users')
->whereBetween('votes', [1, 100])
->get();不在之间 / 或不在之间
该 whereNotBetween 方法验证列的值不在两个值之间:
$users = DB::table('users')
->whereNotBetween('votes', [1, 100])
->get();介于两列之间 / 不介于两列之间 / 或介于两列之间 / 或不介于两列之间
这个 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 方法验证给定值是否位于同一表行中两个同类型列的值之间:
$patients = DB::table('products')
->whereValueBetween(100, ['min_price', 'max_price'])
->get();whereValueNotBetween 方法验证一个值不在同一表格行中两列的值之间:
$patients = DB::table('products')
->whereValueNotBetween(100, ['min_price', 'max_price'])
->get();条件为空 / 条件不为空 / 或条件为空 / 或条件不为空
whereNull 方法验证给定列的值为 NULL:
$users = DB::table('users')
->whereNull('updated_at')
->get();该 whereNotNull 方法验证该列的值不是 NULL:
$users = DB::table('users')
->whereNotNull('updated_at')
->get();在日期 / 在月份 / 在日 / 在年份 / 在时间
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 方法可用于判断列的值是过去还是未来:
$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();where列 / 或where列
该 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')[!WARNING]
您应该始终对orWhere调用进行分组,以避免在应用全局作用域时出现意外行为。
whereExists 方法允许您编写 "where exists" SQL 子句. whereExists 方法接受一个闭包, 它将接收一个查询构建器实例, 允许您定义应该放置在 "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 方法来实现这一点。例如,以下查询将检索所有拥有给定类型"membership"的用户;
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();[!WARNING]
全文 where 子句当前受 MariaDB、MySQL 和 PostgreSQL 支持。
可使用 whereFullText 和 orWhereFullText 方法为具有 [全文索引](/docs/laravel/12.x/zh-cn/migrations#available-index-types) 的列向查询添加全文"where"子句. Laravel 会将这些方法转换为底层数据库系统适用的 SQL. 例如, 将为使用 MariaDB 或 MySQL 的应用生成一个 MATCH AGAINST 子句:
$users = DB::table('users')
->whereFullText('bio', 'web developer')
->get();orderBy 方法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 方法允许您轻松地按日期排序结果。默认情况下,结果将按表的 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 方法来限制查询返回的结果数量,或者跳过查询中给定数量的结果:
$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,则闭包不会被执行。因此,在上述示例中,传递给 when 方法的闭包仅当传入请求中存在 role 字段且其值为 true 时才会被调用。
你可以将另一个闭包作为第三个参数传递给 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 方法接受一个由列名和值组成的数组:
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()->subMonth()));如果表具有一个自增ID,使用 insertGetId 方法插入一条记录并检索该ID:
$id = DB::table('users')->insertGetId(
['email' => 'john@example.com', 'votes' => 0]
);[!WARNING]
When using PostgreSQL theinsertGetIdmethod expects the auto-incrementing column to be namedid. If you would like to retrieve the ID from a different "sequence", you may pass the column name as the second parameter to theinsertGetIdmethod.
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 列。
[!WARNING]
除 SQL Server 外的所有数据库都要求upsert方法的第二个参数中的列具有“主键”或“唯一”索引。此外,MariaDB 和 MySQL 数据库驱动程序会忽略upsert方法的第二个参数,并始终使用表的“主键”和“唯一”索引来检测现有记录。
除了向数据库插入记录之外,查询构建器还可以使用 update 方法更新现有记录。update 方法,与 insert 方法类似,接受一个列和值对的数组,用于指示要更新的列。update 方法返回受影响的行数。你可以使用 where 子句约束 update 查询:
$affected = DB::table('users')
->where('id', 1)
->update(['votes' => 1]);有时您可能希望更新数据库中现有记录,或者在没有匹配记录时创建它。在这种情况下,可以使用 updateOrInsert 方法。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 对象中相应的键。此操作支持 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" 子句来约束 delete 语句:
$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();虽然不是强制性的,但建议将悲观锁包裹在[事务](/docs/laravel/12.x/zh-cn/database#database-transactions)中。这确保了在整个操作完成之前,检索到的数据在数据库中保持不变。如果发生故障,事务将回滚所有更改并自动释放锁:
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();