查询构建器


介绍

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

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

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

运行数据库查询

从表中检索所有行

您可以使用 DB 门面提供的 table 方法来开始查询。table 方法会返回给定表的流畅查询构建器实例,让您可以在查询上链式添加更多约束,然后最后使用 get 方法来检索查询结果:

<?php
 
namespace App\Http\Controllers;
 
use App\Http\Controllers\Controller;
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;

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

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

你可以使用 find 方法通过其 id 列值来检索单个行:

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

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

暂存结果

lazy 方法和 chunk 方法在执行查询时会分块,但是 lazy() 方法在处理每个分块时不会调用回调,而是返回一个 LazyCollection,让你能够像和单一流相交互一样处理结果:

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

同样,如果你计划在迭代它们时更新检索到的记录,则最好使用 lazyByIdlazyByIdDesc 方法。这些方法会根据记录的主键自动分页结果:

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

在迭代它们时更新或删除记录时,对主键或外键的任何更改可能会影响块查询。这可能导致记录没有被包含在结果中。

聚合

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

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

判断记录是否存在

你可以使用 existsdoesntExist 方法,而不是使用 count 方法来确定是否存在符合你查询约束的任何记录:

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

SELECT 语句

指定选择子句

您可能并不总是希望从数据库表中选择所有列。使用 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

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

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

havingRaw / orHavingRaw

havingRaworHavingRaw 方法可用于在 "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();

左连接/右连接子句

如果你想执行"左连接"或"右连接"而不是"内连接",请使用 leftJoinrightJoin 方法。这些方法与 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 实例提供的 whereorWhere 方法。这些方法将列与一个值进行比较,而不是比较两个列的值:

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

子查询连接

您可以使用 joinSubleftJoinSubrightJoinSub 方法将查询连接到子查询。每个方法都接收三个参数:子查询、表别名和定义相关列的闭包。在此示例中,我们将检索包含每个用户记录的最新发布博客文章的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();

联合查询

查询构建器还提供了一个方便的方法来将两个或多个查询"联合"在一起。例如,您可以创建一个初始查询,并使用 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();

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)

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

Where Not子句

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

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

JSON where 子句

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

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

您可以使用 whereJsonContains 来查询 JSON 数组。SQLite 数据库版本低于 3.38.0 不支持此功能:

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

如果应用程序使用 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 子句

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

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
)

如果要在查询中添加大量的整数绑定,可以使用 whereIntegerInRawwhereIntegerNotInRaw 方法来大大减少内存使用。

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')

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

高级的 WHERE 子句

存在 Where 子句

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 子句

有时候你可能需要将一个子查询的结果与给定的值进行比较。你可以通过传递闭包及一个值来实现。例如,下面的查询将会取出所有具有给定类型的最新"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 方法。比如,下面的查询将查找所有收入记录中金额少于平均值的记录:

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 子句

全文本 where 子句目前由 MySQL 和 PostgreSQL 支持。

whereFullTextorWhereFullText 方法可用于对具有全文索引的列添加全文 "where" 子句。这些方法将通过 Laravel 转化为相应数据库系统的合适 SQL。比如,对于使用 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 方法

latestoldest 方法能让你按日期容易的排序结果。默认情况下,结果将按表的 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 方法

正如你所期望的,groupByhaving 方法可用于对查询结果进行分组。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 方法

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

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

或者,你可以使用 limitoffset 方法。这两种方法分别等价于 takeskip 方法:

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

条件子句

有时你可能希望在满足另一个条件的情况下,应用一些查询子句。例如,你可能只想当请求中给定的输入值存在时才应用 where 语句。你可以使用 when 方法来完成:

$role = $request->string('role');
 
$users = DB::table('users')
                ->when($role, function (Builder $query, string $role) {
                    $query->where('role_id', $role);
                })
                ->get();

when 方法只在首个参数为真时执行闭包。如果首个参数为假,闭包将不会被执行。所以在上面的例子中,当传入请求中的 role 字段存在且计算结果为真时,才会调用 when 方法给出的闭包。

你可以传递另一个闭包作为 when 方法的第三个参数。这个闭包只在第一个参数为假时执行。我们将以查询默认排序的配置为例,来说明如何使用这个特性:

$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 方法,可用于向数据库表插入记录。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

如果表中有自增 id,使用 insertGetId 方法可以在插入记录的同时获取ID:

$id = DB::table('users')->insertGetId(
    ['email' => 'john@example.com', 'votes' => 0]
);

当使用 PostgreSQL 时,insertGetId 方法默认自增列的名字是 id。如果你想从不同的"序列"中获取 ID,你可以将列名作为第二个参数传递给 insertGetId 方法。

插入更新

upsert 方法插入不存在的记录,并更新已经存在的记录,给出的新值指定了更新的内容。方法的第一个参数由要插入或更新的值组成,第二个参数列举出在对应的表中唯一标识记录的列名(们)。方法的第三个和最后一个参数是一个数组,列表列出了在数据库已经存在相应的记录时需要更新的列:

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

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

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

UDPATE 语句

除插入记录到数据库之外,查询构建器也可以使用 update 方法更新现有的记录。update 方法接受一个列和值对的数组,这些键值对指出了需要更新的列。update 方法返回影响的行数。你可以使用 where 子句对 update查询进行约束:

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

Update 或 Insert

有时你可能想更新数据库中的现有记录,如果没有匹配的记录,则创建它。在这种情况下,可以使用 updateOrInsert 方法。updateOrInsert 方法接受两个参数:找到记录需要的列和值对的数组,以及更新列需要的列和值对的数组。

updateOrInsert 方法将试图使用第一个参数的列和值对定位一个匹配的数据库记录。如果记录存在,将用第二个参数的值更新它。如果找不到记录,将插入一个新纪录,其属性为两个参数合并后的结果:

DB::table('users')
    ->updateOrInsert(
        ['email' => 'john@example.com', 'name' => 'John'],
        ['votes' => '2']
    );

更新 JSON 列

更新 JSON 列时,你应使用 -> 语法来更新 JSON 对象中的合适键。这个操作在 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']);

此外,您还可以使用 incrementEachdecrementEach 方法同时增加或减少多个列:

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

DELETE 语句

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

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

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

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

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

表截断和 PostgreSQL

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

悲观锁定

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

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

或者,可以使用 lockForUpdate 方法。"for update"锁可防止所选记录被修改或被另一个共享锁选择:

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

调试

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

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

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

可以在查询上调用 dumpRawSqlddRawSql 方法来转储具有正确替换所有参数绑定的查询SQL:

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

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

点赞 取消点赞 收藏 取消收藏

<< 上一篇: 入门指南

>> 下一篇: 分页