介绍
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
{
/**
* 显示应用程序所有用户的列表。
*/
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 方法。在这个例子中,我们将检索一个用户标题的集合:
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 方法。此方法一次检索一小部分结果,并将每个块传递到一个闭包中进行处理。例如,让我们一次以 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) {
// 处理记录...
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]);
}
});[!警告]
在分块回调中更新或删除记录时,对主键或外键的任何更改都可能影响分块查询。这可能会导致记录未包含在分块结果中。
懒加载流式处理结果
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]);
});[!警告]
在迭代时更新或删除记录时,对主键或外键的任何更改都可能影响分块查询。这可能会导致记录未包含在结果中。
聚合函数
查询构建器还提供了多种方法来检索聚合值,如 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');确定记录是否存在
您可以使用 exists 和 doesntExist 方法来确定是否存在与您的查询约束匹配的记录,而不是使用 count 方法:
if (DB::table('orders')->where('finalized', 1)->exists()) {
//...
}
if (DB::table('orders')->where('finalized', 1)->doesntExist()) {
//...
}选择语句
指定选择子句
您可能并不总是想要从数据库表中选择所有列。使用 select 方法,您可以为查询指定自定义的“选择”子句:
use Illuminate\Support\Facades\DB;
$users = DB::table('users')
->select('name', 'email as user_email')
->get();distinct 方法允许您强制查询返回不同的结果:
$users = DB::table('users')->distinct()->get();如果您已经有一个查询构建器实例,并且您希望向其现有的选择子句中添加一个列,您可以使用 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 方法的第一个参数是您需要连接的表的名称,而其余参数指定连接的列约束。您甚至可以在单个查询中连接多个表:
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 方法向查询添加“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();如前所述,您可以使用数据库系统支持的任何操作符:
$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();[!WARNING]
PDO 不支持绑定列名称。因此,您永远不应允许用户输入来决定您的查询所引用的列名称,包括“order by”列。
Or Where 子句
当将查询构建器的 where 方法的调用链接在一起时,“where”子句将使用 and 操作符连接在一起。但是,您可以使用 orWhere 方法使用 or 操作符将一个子句连接到查询中。orWhere 方法接受与 where 方法相同的参数:
$users = DB::table('users')
->where('votes', '>', 100)
->orWhere('name', 'John')
->get();如果您需要将一个“or”条件括在括号内,可以将一个闭包作为第一个参数传递给 orWhere 方法:
$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调用进行分组。
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 方法可用于检索给定列都不符合给定约束的记录:
$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%'
)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();您可以使用 whereJsonContains 来查询 JSON 数组:
$users = DB::table('users')
->whereJsonContains('options->languages', 'en')
->get();如果您的应用程序使用 MariaDB、MySQL 或 PostgreSQL 数据库,您可以将值数组传递给 whereJsonContains 方法:
$users = DB::table('users')
->whereJsonContains('options->languages', ['en', 'de'])
->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();[!WARNING]
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);
$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
)[!WARNING]
如果您要向查询中添加大量整数绑定数组,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();whereNull / whereNotNull / orWhereNull / orWhereNotNull
whereNull 方法验证给定列的值为 NULL:
$users = DB::table('users')
->whereNull('updated_at')
->get();whereNotNull 方法验证列的值不为 NULL:
$users = DB::table('users')
->whereNotNull('updated_at')
->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();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')[!WARNING]
为了避免在应用全局作用域时出现意外行为,您应该始终对orWhere调用进行分组。
高级 Where 子句
存在子句(Where Exists Clauses)
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子句(Subquery Where Clauses)
有时您可能需要构建一个将子查询的结果与给定值进行比较的“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子句(Full Text Where Clauses)
[!WARNING]
全文Where子句目前由MariaDB、MySQL和PostgreSQL支持。
whereFullText和orWhereFullText方法可用于为具有全文索引的列向查询添加全文“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();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();分组
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方法。
限制和偏移
skip和take方法
您可以使用skip和take方法来限制从查询中返回的结果数量或跳过查询中的给定数量的结果:
$users = DB::table('users')->skip(10)->take(5)->get();或者,您可以使用limit和offset方法。这些方法在功能上分别与take和skip方法等效:
$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方法接受一个列名和值的数组:
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的严格模式 (opens in a new tab):
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
如果表具有自增ID,使用insertGetId方法插入一条记录,然后检索该ID:
$id = DB::table('users')->insertGetId(
['email' => 'john@example.com', 'votes' => 0]
);[!WARNING]
当使用PostgreSQL时,insertGetId方法期望自增列名为id。如果您想从不同的“序列”中检索ID,可以将列名作为insertGetId方法的第二个参数传递。
插入或更新(Upserts)
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列时,您应该使用->语法来更新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();如果您希望截断整个表,这将从表中删除所有记录并将自增ID重置为零,您可以使用truncate方法:
DB::table('users')->truncate();表截断和PostgreSQL
在截断PostgreSQL数据库时,将应用CASCADE行为。这意味着其他表中所有与外键相关的记录也将被删除。
悲观锁
查询构建器还包括一些函数,可帮助您在执行select语句时实现“悲观锁”。要使用“共享锁”执行语句,您可以调用sharedLock方法。共享锁会阻止所选行在您的事务提交之前被修改:
DB::table('users')
->where('votes', '>', 100)
->sharedLock()
->get();或者,您可以使用lockForUpdate方法。“for update”锁会阻止所选记录被修改或被另一个共享锁选择:
DB::table('users')
->where('votes', '>', 100)
->lockForUpdate()
->get();调试
在构建查询时,您可以使用dd和dump方法来转储当前的查询绑定和SQL。dd方法将显示调试信息,然后停止执行请求。dump方法将显示调试信息,但允许请求继续执行:
DB::table('users')->where('votes', '>', 100)->dd();
DB::table('users')->where('votes', '>', 100)->dump();您可以在查询上调用dumpRawSql和ddRawSql方法来转储查询的SQL,并正确替换所有参数绑定: