介绍

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

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


警告
PDO 不支持绑定列名。因此,绝不应允许用户输入决定查询中引用的列名,包括 “order by” 列。

运行数据库查询

从表中检索所有记录
可以使用 php DB facade 提供的 php table 方法开始查询。php table 方法为指定表返回链式查询构造器实例,允许在查询上链接更多约束,最后使用 php get 方法检索查询结果:

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Support\Facades\DB;
  4. use Illuminate\View\View;
  5. class UserController extends Controller
  6. {
  7. /**
  8. * 展示应用程序所有用户的列表。
  9. */
  10. public function index(): View
  11. {
  12. $users = DB::table('users')->get();
  13. return view('user.index', ['users' => $users]);
  14. }
  15. }

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

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


注意:
Laravel 集合提供了各种及其强大的方法来映射和裁切数据。有关 Laravel 集合的更多信息,查看 集合文档。

从表中检索单行或单列
如果只需要从数据库表中检索单行,可以使用 php DB facade 中的 php first 方法。 此方法将返回单个 php stdClass 对象:

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

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

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

要通过 php id 列检索单行,使用 php find 方法:

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

获取某一列的值列表
如果要检索包含单个列值的 php Illuminate\Support\Collection 实例,则可以使用 php pluck 方法。在此示例中,将检索 user 表中 title 的集合:

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

可以通过向 php pluck 方法提供第二个参数来指定结果集中应该用作 key 的列:

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

分块结果

如果需要处理数千条数据库记录,可以考虑使用 php DB facade 提供的 php chunk 方法。此方法每次检索一小块结果,并将每个块传入闭包进行处理。例如,每次以 100 条记录为块检索整个 php users 表:

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

可以通过从闭包中返回 php false 来停止处理其余的块:

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

如果在对结果进行分块时更新数据库记录,那分块结果可能会以意想不到的方式更改。如果计划在分块时更新检索到的记录,最好使用 php chunkById 方法。此方法将根据记录的主键自动对结果进行分页:

  1. DB::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. });


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

延迟流式结果

php lazy 方法的工作原理类似于 php chunk 方法,因为都是以块的形式执行查询。但是,php lazy() 方法不是将每个块传递给回调,而是返回 php LazyCollection,可以以单个流的形式与结果进行交互:

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

再次强调,如果打算在迭代时更新检索到的记录,最好使用 php lazyByIdphp lazyByIdDesc 方法。 这些方法将根据记录的主键自动对结果进行分页:

  1. DB::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. });


警告
当在更新或删除块迭代的记录时,对主键或外键的任何更改都可能影响块查询。这可能会导致记录未包含在结果中。

聚合

查询构建器还提供了多种检索聚合值的方法,例如 php countphp maxphp minphp avgphp sum。你可以在构建查询后调用这些方法中的任何一个:

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

当然,你可以将这些方法与其他子句结合起来,以优化计算聚合值的方式:

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

判断记录是否存在
除了通过 php count 方法可以确定查询条件的结果是否存在之外,还可以使用 php existsphp doesntExist 方法:

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

Select 语句

指定一个 Select 语句
可能你并不总是希望从数据库表中获取所有列。 使用 php select 方法,可以自定义一个 「select」 查询语句来查询指定的字段:

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

php distinct 方法会强制让查询返回的结果不重复:

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

如果你已经有了一个查询构造器实例,并且希望在现有的查询语句中加入一个字段,那么你可以使用 php addSelect 方法:

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

原始表达式

需要在某个查询中插入特定的字符串时,可以使用 php DB 门面提供的 php 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注入漏洞。

原始方法

除了使用 php DB::raw 方法以外,还可以使用以下方法将原始表达式插入查询中。 注意,Laravel 无法保证任何使用原始表达式的查询免疫SQL注入漏洞。

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

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

whereRaw / orWhereRaw
php whereRawphp orWhereRaw 方法可以用于将原始的「where」子句注入查询。这两个方法接收一个可选的绑定数组作为它们的第二个参数:

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

havingRaw / orHavingRaw
php havingRawphp orHavingRaw 方法可以用于将原始的字符串作为「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
php orderByRaw 方法可用于将原生字符串设置为「order by」子句的值:

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

groupByRaw

php groupByRaw 方法可以用于将原生字符串设置为 php group by 子句的值:

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

Joins

Inner Join 子句
查询构造器也还可用于向查询中添加连接子句。若要执行基本的「inner join」,你可以对查询构造器实例使用 php join 方法。传递给 php join 方法的第一个参数是需要你连接到的表的名称,而其余参数指定连接的列约束。你甚至还可以在一个查询中连接多个表:

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

Left Join / Right Join 子句
如果你想使用「left join」或者「right join」代替「inner join」,可以使用 php leftJoin 或者 php rightJoin 方法。这两个方法与 php join 方法用法相同:

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

交叉连接子句
你可以使用 php crossJoin 方法来执行「交叉连接」。交叉连接会在第一个表和连接的表之间生成笛卡尔积:

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

高级连接子句
你也可以指定更高级的连接子句。为此,可以将一个闭包作为 php join 方法的第二个参数传递。该闭包将接收到一个 php Illuminate\Database\Query\JoinClause 实例,允许你对「join」子句指定约束:

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

如果你想在连接中使用 「where」子句,可以使用 php JoinClause 实例提供的 php wherephp orWhere 方法。这些方法不是比较两个列,而是将列与一个值进行比较:

  1. DB::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();

子查询连接
你可以使用 php joinSubphp leftJoinSubphp rightJoinSub 方法将查询与子查询连接起来。这些方法接收三个参数:子查询、子查询的表别名,以及定义相关列的闭包。在这个例子中,我们将检索一组用户,其中每个用户记录还包含用户最新发布的博客文章的 php 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. $users = DB::table('users')
  6. ->joinSub($latestPosts, 'latest_posts', function (JoinClause $join) {
  7. $join->on('users.id', '=', 'latest_posts.user_id');
  8. })->get();

横向连接


[!警告]
横向连接目前由 PostgreSQL、MySQL >= 8.0.14 和 SQL Server 支持。


你可以使用 php joinLateralphp leftJoinLateral 方法来执行与子查询的「横向连接」。这些方法接收两个参数:子查询和子查询的表别名。连接条件应在给定子查询的 php where 子句中指定。横向连接针对每一行进行评估,并且可以引用子查询外部的列。

在这个例子中,我们将检索一组用户以及用户的三个最新博客文章。每个用户在结果集中最多可以产生三行:每个用户最新的三篇博客文章各占一行。连接条件在子查询中使用 php 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. $users = DB::table('users')
  7. ->joinLateral($latestPosts, 'latest_posts')
  8. ->get();

联合查询

查询构建器还提供了一种便捷的方法,用于将两个或多个查询「联合」在一起。例如,你可以创建一个初始查询,并使用 php union 方法将其与更多查询联合起来:

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

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

基本 Where 子句

Where 子句

你可以使用查询构建器的 php where 方法向查询添加「where」子句。对 php where 方法最基本的调用需要三个参数。第一个参数是列的名称。第二个参数是一个操作符,可以是数据库支持的任何操作符。第三个参数是与列的值进行比较的值。

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

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

为了方便起见,如果你想验证一个列是否等于给定值,可以将该值作为 php where 方法的第二个参数传递。Laravel 会假设你想使用 php = 操作符:

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

如前所述,你可以使用数据库系统支持的任何操作符:

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

你也可以将一个条件数组传递给 php where 函数。数组的每个元素应该是一个包含通常传递给 php where 方法的三个参数的数组:

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


[!警告]
PDO 不支持绑定列名。因此,你万万不可允许用户输入来决定查询中引用的列名,包括「order by」列。

Or Where 子句

当在查询构建器的 php where 方法之间进行链式调用时,「where」子句将使用 php and 操作符连接在一起。然而,你可以使用 php orWhere 方法使用 php or 操作符将子句连接到查询中。php orWhere 方法接受与 php where 方法相同的参数:

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

如果你需要在括号内分组一个 「or」条件,可以将一个闭包作为 php orWhere 方法的第一个参数传递:

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

上述示例将生成以下 SQL:

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


[!警告]
你应始终对 php orWhere 调用进行分组,以避免在应用全局作用域时出现意外行为。

Where Not 子句

php whereNotphp orWhereNot 方法可用于否定一组给定的查询约束条件。例如,以下查询排除正在清仓的产品或价格低于 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 子句

有时你可能需要对多列采用相同的查询约束。例如,你可能想要检索给定列表中任何列与给定值 php LIKE 匹配的所有记录。你可以使用 php whereAny 方法来实现这一点:

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

上面的查询将产生以下 SQL :

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

类似地,php whereAll 方法可用于检索所有给定列都与给定条件匹配的记录:

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

上面的查询将产生以下 SQL :

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

JSON Where 子句

Laravel 还支持具有 JSON 列类型数据库上查询 JSON 列类型。目前,这包括 MySQL 8.0+、PostgreSQL 12.0+、SQL Server 2017+ 和 SQLite 3.39.0+(带有 JSON1 扩展)。要查询 JSON 列,请使用 php -> 操作符:

  1. $users = DB::table('users')
  2. ->where('preferences->dining->meal', 'salad')
  3. ->get();

你可以使用 php whereJsonContains 来查询JSON数组:

  1. $users = DB::table('users')
  2. ->whereJsonContains('options->languages', 'en')
  3. ->get();

如果你的应用程序使用 MySQL 或 PostgreSQL 数据库,你可以将一个值数组传递给 php whereJsonContains 方法:

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

你可以使用 php whereJsonLength 方法按长度查询 JSON 数组:

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

附加 Where 子句

whereBetween / orWhereBetween

php whereBetween 方法验证一个列的值是否在两个值之间:

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

whereNotBetween / orWhereNotBetween

php whereNotBetween 方法验证一个列的值是否在两个值之外:

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

whereBetweenColumns / whereNotBetweenColumns / orWhereBetweenColumns / orWhereNotBetweenColumns

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

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

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

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

whereIn / whereNotIn / orWhereIn / orWhereNotIn

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

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

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

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

你也可以将一个查询对象作为 php whereIn 方法的第二个参数:

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

上述示例将生成以下 SQL:

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


[!警告]
如果你向查询中添加大量整数绑定,可以使用 php whereIntegerInRawphp whereIntegerNotInRaw 方法来大大减少内存使用。


whereNull / whereNotNull / orWhereNull / orWhereNotNull

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

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

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

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

whereDate / whereMonth / whereDay / whereYear / whereTime

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

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

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

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

php whereDay 方法可用于将列的值与月份的某一天进行比较:

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

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

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

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

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

whereColumn / orWhereColumn

php whereColumn 方法可用于验证两个列是否相等:

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

你也可以向 php whereColumn 方法传递一个比较操作符:

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

你也可以向 php whereColumn 方法传递一个列比较数组。这些条件将使用 php and 操作符连接在一起:

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

逻辑分组

有时你可能需要在括号内分组多个「where」子句,以便实现查询所需的逻辑分组。其实,为避免意外的查询行为,你应始终对 php orWhere 方法的调用分组在括号内。为此,你可以将一个闭包传递给 php 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();

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

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


[!警告]
你应始终对 php orWhere 调用进行分组,以避免在应用全局作用域时出现意外行为。

高级 Where 子句

Where Exists 子句

php whereExists 方法允许你编写「where exists」 SQL 子句。php 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();

或者,你可以将一个查询对象提供给 php whereExists 方法,而不是闭包:

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

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

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

子查询 Where 子句

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

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

或者,你可能需要构建一个「where」子句,将一列与子查询的结果进行比较。你可以通过向 php where 方法传递一个列、操作符和闭包来实现这一点。例如,以下查询将检索所有金额小于平均值的收入记录;

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

全文 Where 子句


[!警告]
全文 where 子句目前由 MySQL 和 PostgreSQL 支持。


php whereFullTextphp orWhereFullText 方法可用于为具有全文索引的列添加全文「where」子句。这些方法将由 Laravel 转换成适合的 SQL 给底层数据库系统。例如,对于使用 MySQL 的应用程序,将生成一个 php MATCH AGAINST 子句:

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

排序、分组、条数限制和偏移量

排序

orderBy 方法
php orderBy 方法允许你按给定列对查询结果进行排序。php orderBy 方法接受的第一个参数应该是你要排序的列,而第二个参数确定排序方向,可以是 php ascphp desc

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

要按多个列排序,你可以简单地按需多次调用 php orderBy

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

latestoldest 方法
php latestphp oldest 方法允许你按日期轻松排序结果。默认情况下,结果将按表的 php created_at 列排序。或者,你可以传递要排序的列名:

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

随机排序
php inRandomOrder 方法可用于随机排序查询结果。例如,你可以使用此方法获取一个随机用户:

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

移除现有排序
php reorder 方法移除已应用于查询的所有「order by」子句:

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

你可以在调用 php reorder 方法时传递列和方向,以便移除所有现有的「order by」子句,并为查询应用一个全新的排序:

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

分组

groupByhaving 方法
如你所料,php groupByphp having 方法可用于对查询结果进行分组。php having 方法的签名类似于 php where 方法:

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

你可以使用 php 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();

你可以向 php groupBy 方法传递多个参数,以按多个列进行分组:

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

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

条数限制和偏移量

skiptake 方法
你可以使用 php skipphp take 方法来限制从查询返回的结果数量,或者在查询中跳过给定数量的结果:

  1. $users = DB::table('users')->skip(10)->take(5)->get();

或者,你可以使用 php limitphp offset 方法。这些方法在功能上分别等同于 php takephp skip 方法:

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

前提子句

有时你可能希望根据另一个条件将某些查询子句应用于查询。例如,如果给定的输入值存在于传入的 HTTP 请求中,你可能只想应用一个 php where 语句。你可以使用 php when 方法来实现这一点:

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

php when 方法仅在第一个参数为 php true 时执行给定的闭包。如果第一个参数为 php false,闭包将不会执行。因此,在上面的示例中,传递给 php when 方法的闭包仅在 php role 字段存在于传入请求中且评估为 php true 时才会被调用。

你可以将另一个闭包作为 php when 方法的第三个参数传递。这个闭包仅在第一个参数评估为 php false 时才会执行。为了说明如何使用此功能,我们将使用它来配置查询的默认排序:

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

插入语句

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

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

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

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

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

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

当使用子查询确定应插入的数据时候,php insertUsing 方法会将新记录插入进表中:

  1. DB::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()->subMonth()));

自增 ID
如果表有一个自增 ID,使用 php insertGetId 方法插入记录并检索 ID:

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


[!警告]
当使用 PostgreSQL 时,php insertGetId 方法期望自增列名为 php id。如果你想从不同的「序列」中检索 ID,可以将列名作为 php insertGetId 方法的第二个参数传递。

更新插入

php upsert 方法将插入不存在的记录,并更新已存在的记录为指定的新值。方法的第一个参数包含要插入或更新的值,而第二个参数列出关联表中唯一标识记录的列。方法的第三个也是最后一个参数是一个列数组,如果数据库中已存在匹配记录,则应更新这些列:

  1. DB::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 将尝试插入两条记录。如果记录已存在相同的 php departurephp destination 列值,Laravel 将更新该记录的 php price 列。


[!警告]
除 SQL Server 外的所有数据库都要求 php upsert 方法的第二个参数中的列具有「主键」或「唯一」索引。此外,MySQL 数据库驱动程序忽略 php upsert 方法的第二个参数,并始终使用表的「主键」或「唯一」索引来检测现有记录。

更新语句

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

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

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

php updateOrInsert 方法将尝试使用第一个参数的列和值对查找匹配的数据库记录。如果记录存在,将使用第二个参数中的值进行更新。如果记录找不到,将插入一个新记录,其属性为两个参数的合并:

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

你可以向 php updateOrInsert 方法提供一个闭包,以根据匹配记录的存在自定义更新或插入到数据库中的属性:

  1. DB::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 列的收,你可以使用 php -> 语法来更新 JSON 对象中恰当的键。此操作需要 MySQL 5.7+ 和 PostgreSQL 9.5+ 的数据库:

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

自增与自减

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

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

你还可以在操作期间指定要更新的其他列:

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

此外,你可以使用 php incrementEachphp decrementEach 方法同时增加或减少多个列:

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

删除语句

查询构建器的 php delete方法可用于从表中删除记录。php delete 方法返回受影响的行数。你可以通过在调用 php delete 方法之前添加 “where” 子句来限制 php delete 语句:

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

如果你希望清空整个表,这将从表中删除所有记录并将自动递增 ID 重置为零,你可以使用 php truncate 方法:

  1. DB::table('users')->truncate();

表清空 和 PostgreSQL
当清空一个 PostgreSQL 数据库时,将应用 php CASCADE 行为。这意味着其他表中所有与外键相关联的记录也将被删除。

悲观锁

查询构建器还包括一些函数,可帮助你在执行 php select 语句时实现「悲观锁」。 要使用「共享锁」执行语句,你可以调用 php sharedLock 方法。共享锁可防止选定的行被修改,直到你的事务被提交:

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

或者,你可以使用 php lockForUpdate 方法。「update」锁可防止所选记录被修改或被另一个共享锁选中:

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

调试

你可以在构建查询时使用 php ddphp dump 方法来转储当前查询绑定和 SQL。 php dd 方法来转储当前查询绑定和 SQL。 php dump 方法将显示调试信息,但允许请求继续执行:

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

可以在查询上调用 php dumpRawSqlphp ddRawSql 方法,以转储查询的 SQL,并且所有参数绑定均正确替换:

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