简介

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

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

PDO 不支持绑定列名。因此,永远不要允许用户输入决定查询所引用的列名,包括 “order by” 列。

运行数据库查询

从表中检索所有行

你可以使用 DB 门面提供的 table 方法来开启一个查询。table 方法会返回给定表的流畅查询构造器实例,允许你向查询链式添加更多约束,最后使用 get 方法获取查询结果:

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

class UserController extends Controller
{
    /**
     * Show a list of all of the application's users.
     */
    public function index(): View
    {
        $users = DB::table('users')->get();

        return view('user.index', ['users' => $users]);
    }
}

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

use Illuminate\Support\Facades\DB;

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

foreach ($users as $user) {
    echo $user->name;
}

Laravel 集合提供了多种极其强大的方法来映射和归约数据。若要了解 Laravel 集合的更多信息,请查看集合文档。

从表中检索单行/单列

如果你只需要从数据库表中检索单行,可以使用 DB 门面的 first 方法。该方法会返回单个 stdClass 对象:

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

return $user->email;

如果你想从数据库表中检索单行,但在未找到匹配行时抛出 Illuminate\Database\RecordNotFoundException,可以使用 firstOrFail 方法。若未捕获 RecordNotFoundException,系统会自动向客户端返回 404 HTTP 响应:

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

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

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

若要根据 id 列的值检索单行,请使用 find 方法:

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

检索列值列表

如果你希望检索一个 Illuminate\Support\Collection 实例,其中包含单个列的值,可以使用 pluck 方法。在这个例子中,我们将检索用户标题的集合:

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) {
    // 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]);
    });

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

聚合

查询构造器还提供了多种用于检索聚合值的方法,如 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 方法,你可以为查询指定自定义的 “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 实例,从而允许你指定“join”子句的约束条件:

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();

横向连接

横向连接目前支持 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;

$usersWithoutFirstName = DB::table('users')
    ->whereNull('first_name');

$users = DB::table('users')
    ->whereNull('last_name')
    ->union($usersWithoutFirstName)
    ->get();

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

基础 Where 子句

Where 子句

你可以使用查询构造器的 where 方法向查询中添加“where”子句。对 where 方法最基础的调用需要三个参数。第一个参数是列名。第二个参数是运算符,可以是数据库支持的任意运算符。第三个参数是用于与列值进行比较的值。

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

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

为方便起见,如果你想验证某列是否 = 给定值,可以将该值作为第二个参数传递给 where 方法。Laravel 会假定你要使用 = 运算符:

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

你也可以为 where 方法提供一个关联数组,以便快速对多个列进行查询:

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

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

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

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

$users = DB::table('users')
    ->where('name', 'like', 'T%')
    ->get();

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

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

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

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

或(Or)Where 子句

当将查询构建器的 where 方法调用串联起来时,这些“where”子句会使用 and 运算符连接在一起。不过,您可以使用 orWhere 方法,通过 or 运算符将子句与查询连接起来。orWhere 方法接受与 where 方法相同的参数:

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

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

use Illuminate\Database\Query\Builder;

$users = DB::table('users')
    ->where('votes', '>', 100)
    ->orWhere(function (Builder $query) {
        $query->where('name', 'Abigail')
            ->where('votes', '>', 50);
        })
    ->get();

上述示例将生成以下 SQL:

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

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

Where Not 子句

可以使用 whereNot 和 orWhereNot 方法来否定一组给定的查询约束。例如,下面的查询会排除处于清仓状态或价格低于 10 的产品:

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

Where Any / All / None 子句

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

$users = DB::table('users')
    ->where('active', true)
    ->whereAny([
        'name',
        'email',
        'phone',
    ], 'like', 'Example%')
    ->get();

上述查询将生成以下 SQL:

SELECT *
FROM users
WHERE active = true AND (
    name LIKE 'Example%' OR
    email LIKE 'Example%' OR
    phone LIKE 'Example%'
)

同样,可以使用 whereAll 方法来检索所有给定列都符合给定约束的记录:

$posts = DB::table('posts')
    ->where('published', true)
    ->whereAll([
        'title',
        'content',
    ], 'like', '%Laravel%')
    ->get();

上述查询将生成以下 SQL:

SELECT *
FROM posts
WHERE published = true AND (
    title LIKE '%Laravel%' AND
    content LIKE '%Laravel%'
)

可以使用 whereNone 方法来检索所有给定列都不符合给定约束的记录:

$albums = DB::table('albums')
    ->where('published', true)
    ->whereNone([
        'title',
        'lyrics',
        'tags',
    ], 'like', '%explicit%')
    ->get();

上述查询将生成以下 SQL:

SELECT *
FROM albums
WHERE published = true AND NOT (
    title LIKE '%explicit%' OR
    lyrics LIKE '%explicit%' OR
    tags LIKE '%explicit%'
)

JSON Where 子句

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

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

$users = DB::table('users')
    ->whereIn('preferences->dining->meal', ['pasta', 'salad', 'sandwiches'])
    ->get();

您可以使用 whereJsonContains 和 whereJsonDoesntContain 方法来查询 JSON 数组:

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

$users = DB::table('users')
    ->whereJsonDoesntContain('options->languages', 'en')
    ->get();

如果您的应用程序使用 MariaDB、MySQL 或 PostgreSQL 数据库,您可以向 whereJsonContains 和 whereJsonDoesntContain 方法传递一个值数组:

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

$users = DB::table('users')
    ->whereJsonDoesntContain('options->languages', ['en', 'de'])
    ->get();

此外,您可以使用 whereJsonContainsKey 或 whereJsonDoesntContainKey 方法来检索包含或不包含某个 JSON 键的结果:

$users = DB::table('users')
    ->whereJsonContainsKey('preferences->dietary_requirements')
    ->get();

$users = DB::table('users')
    ->whereJsonDoesntContainKey('preferences->dietary_requirements')
    ->get();

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

$users = DB::table('users')
    ->whereJsonLength('options->languages', 0)
    ->get();

$users = DB::table('users')
    ->whereJsonLength('options->languages', '>', 1)
    ->get();

其他 Where 子句

whereLike / orWhereLike / whereNotLike / orWhereNotLike

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

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

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

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

orWhereLike 方法允许您添加带有 LIKE 条件的“or”子句:

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

whereNotLike 方法允许您向查询添加“NOT LIKE”子句:

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

同样,您可以使用 orWhereNotLike 来添加带有 NOT LIKE 条件的“or”子句:

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

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

whereIn / whereNotIn / orWhereIn / orWhereNotIn

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

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

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

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

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

$activeUsers = DB::table('users')->select('id')->where('is_active', 1);

$comments = DB::table('comments')
    ->whereIn('user_id', $activeUsers)
    ->get();

上述示例将生成以下 SQL:

select * from comments where user_id in (
    select id
    from users
    where is_active = 1
)

如果要向查询中添加大量整数绑定,可以使用 whereIntegerInRaw 或 whereIntegerNotInRaw 方法,从而大幅降低内存占用。

whereBetween / orWhereBetween

whereBetween 方法用于验证某个列的值是否处于两个值之间:

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

whereNotBetween / orWhereNotBetween

whereNotBetween 方法用于验证某个列的值是否处于两个值之外:

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

whereBetweenColumns / whereNotBetweenColumns / orWhereBetweenColumns / orWhereNotBetweenColumns

whereBetweenColumns 方法用于验证某个列的值是否处于同一行中另外两列的值之间:

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

whereNotBetweenColumns 方法用于验证某个列的值是否处于同一行中另外两列的值之外:

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

whereValueBetween / whereValueNotBetween / orWhereValueBetween / orWhereValueNotBetween

whereValueBetween 方法用于验证给定值是否处于同一行中两个同类型列的值之间:

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

whereValueNotBetween 方法用于验证某个值是否处于同一行中另外两列的值之外:

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

whereNull / whereNotNull / orWhereNull / orWhereNotNull

whereNull 方法用于验证指定列的值是否为 NULL:

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

whereNotNull 方法用于验证某列的值是否不为 NULL:

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

whereNullSafeEquals / orWhereNullSafeEquals

可使用 whereNullSafeEquals 和 orWhereNullSafeEquals 方法将某列的值与给定值进行比较,同时将两个 NULL 值视为相等:

$lastLoginIp = $request->input('last_login_ip');

$users = DB::table('users')
    ->whereNullSafeEquals('last_login_ip', $lastLoginIp)
    ->get();

whereDate / whereMonth / whereDay / whereYear / whereTime

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

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

可使用 whereMonth 方法将某列的值与指定月份进行比较:

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

可使用 whereDay 方法将某列的值与月份中的指定日期进行比较:

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

可使用 whereYear 方法将某列的值与指定年份进行比较:

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

可使用 whereTime 方法将某列的值与指定时间进行比较:

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

wherePast / whereFuture / whereToday / whereBeforeToday / whereAfterToday

可使用 wherePast 和 whereFuture 方法判断某列的值是否处于过去或未来:

$invoices = DB::table('invoices')
    ->wherePast('due_at')
    ->get();

$invoices = DB::table('invoices')
    ->whereFuture('due_at')
    ->get();

可使用 whereNowOrPast 和 whereNowOrFuture 方法判断某列的值是否处于过去或未来,包含当前日期和时间:

$invoices = DB::table('invoices')
    ->whereNowOrPast('due_at')
    ->get();

$invoices = DB::table('invoices')
    ->whereNowOrFuture('due_at')
    ->get();

可分别使用 whereToday、whereBeforeToday 和 whereAfterToday 方法判断某列的值是否为今天、今天之前或今天之后:

$invoices = DB::table('invoices')
    ->whereToday('due_at')
    ->get();

$invoices = DB::table('invoices')
    ->whereBeforeToday('due_at')
    ->get();

$invoices = DB::table('invoices')
    ->whereAfterToday('due_at')
    ->get();

同样,可使用 whereTodayOrBefore 和 whereTodayOrAfter 方法判断某列的值是否为今天之前或今天之后,包含今天的日期:

$invoices = DB::table('invoices')
    ->whereTodayOrBefore('due_at')
    ->get();

$invoices = DB::table('invoices')
    ->whereTodayOrAfter('due_at')
    ->get();

whereColumn / orWhereColumn

可使用 whereColumn 方法验证两列是否相等:

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

也可向 whereColumn 方法传入比较运算符:

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

还可向 whereColumn 方法传入列比较数组。这些条件会使用 and 运算符连接:

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

逻辑分组

有时可能需要在括号内对多个 “where” 子句进行分组,以实现查询所需的逻辑分组。实际上,通常应始终将 orWhere 方法的调用放入括号内,以避免产生意料之外的查询行为。为实现这一点,可以向 where 方法传入一个闭包:

$users = DB::table('users')
    ->where('name', '=', 'John')
    ->where(function (Builder $query) {
        $query->where('votes', '>', 100)
            ->orWhere('title', '=', 'Admin');
    })
    ->get();

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

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

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

高级 Where 子句

Where Exists 子句

可使用 whereExists 方法编写 “where exists” SQL 子句。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”子句,用于将子查询的结果与给定值进行比较。你可以通过向 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 子句

目前,MariaDB、MySQL 和 PostgreSQL 支持全文 where 子句。

whereFullText 和 orWhereFullText 方法可用于为那些具有全文索引的列,向查询中添加全文“where”子句。Laravel 会将这些方法转换为底层数据库系统所对应的 SQL。例如,对于使用 MariaDB 或 MySQL 的应用程序,将生成 MATCH AGAINST 子句:

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

向量相似度子句

在使用 pgvector 扩展的 PostgreSQL 连接以及 MariaDB 11.7 及以上版本中,支持向量相似度子句。若想了解有关定义向量列和索引的信息,请参阅迁移文档。

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

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

当传入普通字符串作为向量参数时,Laravel 会使用Laravel AI SDK自动为其生成嵌入向量:

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

默认情况下,whereVectorSimilarTo 还会按距离对结果进行排序(最相似的排在最前)。你可以通过传入 false 作为 order 参数来禁用这种排序:

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

如果你需要更多的控制,可以独立使用 selectVectorDistance、whereVectorDistanceLessThan 和 orderByVectorDistance 方法:

$documents = DB::table('documents')
    ->select('*')
    ->selectVectorDistance('embedding', $queryEmbedding, as: 'distance')
    ->whereVectorDistanceLessThan('embedding', $queryEmbedding, maxDistance: 0.3)
    ->orderByVectorDistance('embedding', $queryEmbedding)
    ->limit(10)
    ->get();

在使用 PostgreSQL 时,在能够创建 vector 列之前,必须先加载 pgvector 扩展:

Schema::ensureVectorExtensionExists();

排序、分组、限制和偏移

排序

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 方法

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();

只有当第一个参数为 true 时,when 方法才会执行给定的闭包。如果第一个参数为 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' => '[email protected]',
    'votes' => 0
]);

你可以通过传入由多个数组组成的数组,一次性插入多条记录。每个数组代表一条应插入到表中的记录:

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

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

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

insertUsing 方法会使用子查询来确定要插入的数据,将新记录插入到表中:

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

自增 ID

如果表具有自增 id,请使用 insertGetId 方法插入记录,然后获取该记录的 ID:

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

当使用 PostgreSQL 时,insertGetId 方法要求自增列的名称为 id。如果你想从其他“序列”中获取 ID,可以将列名作为第二个参数传递给 insertGetId 方法。

Upsert

upsert 方法会插入不存在的记录,并更新已存在的记录,将其更新为你指定的新值。该方法的第一个参数是用于插入或更新的值,第二个参数列出了在关联表中唯一标识记录的列。该方法的第三个也是最后一个参数是一个列数组,当数据库中已存在匹配记录时,这些列会被更新:

DB::table('flights')->upsert(
    [
        ['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99],
        ['departure' => 'Chicago', 'destination' => 'New York', 'price' => 150]
    ],
    ['departure', 'destination'],
    ['price']
);

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

除 SQL Server 外,所有数据库都要求 upsert 方法第二个参数中的列具有“主键”或“唯一”索引。此外,MariaDB 和 MySQL 数据库驱动会忽略 upsert 方法的第二个参数,始终使用表的“主键”和“唯一”索引来检测已存在的记录。

更新语句

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

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

更新或插入

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

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

DB::table('users')
    ->updateOrInsert(
        ['email' => '[email protected]', '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();

悲观锁

查询构造器还包含一些功能,可帮助你在执行 select 语句时实现“悲观锁”。若要执行带“共享锁”的语句,可以调用 sharedLock 方法。共享锁会阻止所选行在事务提交前被修改:

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

另外,你也可以使用 lockForUpdate 方法。“for update”锁会阻止所选记录被修改,也阻止其他共享锁对其再次选择:

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

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

DB::transaction(function () {
    $sender = DB::table('users')
        ->lockForUpdate()
        ->find(1);

    $receiver = DB::table('users')
        ->lockForUpdate()
        ->find(2);

    if ($sender->balance < 100) {
        throw new RuntimeException('Balance too low.');
    }

    DB::table('users')
        ->where('id', $sender->id)
        ->update([
            'balance' => $sender->balance - 100
        ]);

    DB::table('users')
        ->where('id', $receiver->id)
        ->update([
            'balance' => $receiver->balance + 100
        ]);
});

可复用的查询组件

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

use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;

$destination = $request->query('destination');

DB::table('flights')
    ->when($destination, function (Builder $query, string $destination) {
        $query->where('destination', $destination);
    })
    ->orderByDesc('price')
    ->get();

// ...

$destination = $request->query('destination');

DB::table('flights')
    ->when($destination, function (Builder $query, string $destination) {
        $query->where('destination', $destination);
    })
    ->where('user', $request->user()->id)
    ->orderBy('destination')
    ->get();

您可能需要将查询中通用的目标地过滤逻辑提取到一个可复用的对象中:

<?php

namespace App\Scopes;

use Illuminate\Database\Query\Builder;

class DestinationFilter
{
    public function __construct(
        private ?string $destination,
    ) {
        //
    }

    public function __invoke(Builder $query): void
    {
        $query->when($this->destination, function (Builder $query) {
            $query->where('destination', $this->destination);
        });
    }
}

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


use App\Scopes\DestinationFilter;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;

DB::table('flights')
    ->when($destination, function (Builder $query, string $destination) {
        $query->where('destination', $destination);
    })
    ->tap(new DestinationFilter($destination))
    ->orderByDesc('price')
    ->get();

// ...

DB::table('flights')
    ->when($destination, function (Builder $query, string $destination) {
        $query->where('destination', $destination);
    })
    ->tap(new DestinationFilter($destination))
    ->where('user', $request->user()->id)
    ->orderBy('destination')
    ->get();

查询管道(Query Pipes)

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();