查询构造器

未匹配的标注
本文档最新版为 10.x,旧版本可能放弃维护,推荐阅读最新版!

数据库:查询构造器

简介

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

Laravel 的查询构造器使用 PDO 参数绑定的形式,来保护您的应用程序免受 SQL 注入攻击。因此不必清理因参数绑定而传入的字符串。

注意:PDO 不支持绑定列名。因此,不能让用户通过输入的方式,来指定查询语句从而引用的列名,包括 order by 字段等等。如果必须通过查询用户选择的方式引入的某些列,请始终根据允许列的白名单来校验列名。

运行数据库查询

从表中检索所有行

你可以使用 DB facade 里的 table 方法来开始查询。table 方法为给定的表返回一个查询构造器实例,允许你在查询上链式调用更多的约束,最后使用 get 方法获取结果:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class UserController extends Controller
{
    /**
     * 展示所有用户数据。
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $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 集合, 请访问 文档.

从数据表中获取单行或单列

如果你只需要从数据表中获取一行数据,你可以使用 first 方法。该方法返回一个 StdClass 对象:

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

return $user->email;

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

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

如果是通过 id 字段值获取一行数据,可以使用 find 方法:

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

获取一列的值

如果你想获取包含单列值的集合,则可以使用 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提供的方法。 这个方法一次检索一小块结果,并将每个块反馈到闭包函数中进行处理。 例如,让我们以一次100条记录的块为单位检索整个users表。:

use Illuminate\Support\Facades\DB;

DB::table('users')->orderBy('id')->chunk(100, function ($users) {
    foreach ($users as $user) {
        //
    }
});

您可以通过从闭包中返回false来停止处理其他块:

DB::table('users')->orderBy('id')->chunk(100, function ($users) {
    // Process the records...

    return false;
});

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

DB::table('users')->where('active', false)
    ->chunkById(100, function ($users) {
        foreach ($users as $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');

判断记录是否存在

除了通过 count 方法可以确定查询条件的结果是否存在之外,还可以使用 exists 和 doesntExist 方法:

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

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

Select 说明

指定一个 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 方法可以代替 select(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();

Joins

Inner Join 语句

查询构造器也可以编写 join 方法。若要执行基本的「内链接」,你可以在查询构造器实例上使用 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();

Left Join / Right Join Clause

如果你想使用 「左连接」或者 「右连接」代替「内连接」 ,可以使用 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();

Cross Join 语句

你可以使用 crossJoin 方法和你想要连接的表名做「交叉连接」。交叉连接在第一个表和被连接的表之间会生成笛卡尔积:

$sizes = DB::table('sizes')
            ->crossJoin('colors')
            ->get();

高级 Join 语句

你还可以指定更高级的 join 语句。比如传递一个闭包作为 join 方法的第二个参数。此闭包接收一个 Illuminate\Database\Query\JoinClause 对象,从而指定 join 语句中指定的约束:

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

如果你想要在连接上使用「where」 风格的语句,你可以在连接上使用 JoinClause 实例中的 whereorWhere 方法。这些方法会将列和值进行比较,而不是列和列进行比较:

DB::table('users')
        ->join('contacts', function ($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 ($join) {
            $join->on('users.id', '=', 'latest_posts.user_id');
        })->get();

Unions

查询构造器还提供了一种简洁的方式将两个或者多个查询联合在一起。例如,你可以先创建一个查询,然后使用 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 方法需要三个基本参数。第一个参数是字段的名称。第二个参数是一个操作符,它可以是数据库中支持的任意操作符。第三个参数是与字段比较的值。

例如。在 users 表中查询 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 方法的数组中的每一个元素都应该包含 3 个元素:

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

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($query) {
                $query->where('name', 'Abigail')
                      ->where('votes', '>', 50);
            })
            ->get();

上面的例子将会生成下面的 SQL:

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

注意:为了避免应用全局作用出现意外,您应该用 orWhere 调用这个分组。

JSON Where 语句

Laravel 也支持 JSON 类型的字段查询,前提是数据库也支持 JSON 类型。目前,有 MySQL 5.7+、PostgreSQL、SQL Server 2016 和 SQLite 3.9.0 支持 JSON 类型 (with the JSON1 extension)。可以使用 -> 操作符来查询 JSON 字段:

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

您可以使用 whereJsonContains 方法来查询 JSON 数组。但是 SQLite 数据库不支持该功能:

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

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

注意:如果您在查询中用到了一个很大的数组,那么可以使用 whereIntegerInRaw 方法或者 whereIntegerNotInRaw 方法来减少内存的使用量。

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 ($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 ($query) {
               $query->select(DB::raw(1))
                     ->from('orders')
                     ->whereColumn('orders.user_id', 'users.id');
           })
           ->get();

上述查询将产生如下的 SQL 语句:

select * from users
where exists (
    select 1
    from orders
    where orders.user_id = users.id
)

子查询 Where 语句

有时候,您可能需要构造一个 where 子句,将子查询的结果与给定值进行比较。您可以通过向 where 方法传递一个闭包和一个值来完成此操作。例如,下面的查询将检索最后一次「会员」购买记录是 「Pro」 类型的所有用户:

use App\Models\User;

$users = User::where(function ($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;

$incomes = Income::where('amount', '<', function ($query) {
    $query->selectRaw('avg(i.amount)')->from('incomes as i');
})->get();

Ordering, Grouping, Limit & Offset

Ordering

The orderBy Method

orderBy 方法允许你通过给定字段对结果集进行排序。 orderBy 的第一个参数应该是你希望排序的字段,第二个参数控制排序的方向,可以是 ascdesc

$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 方法允许你删除已经存在的所有排序,如果你愿意,可以在之后附加一个新的排序。例如,你可以删除所有已存在的排序:

$query = DB::table('users')->orderBy('name');

$unorderedUsers = $query->reorder()->get();

删除所有已存在的排序并且附加新的排序,并且在方法上提供新的排序字段和顺序,用于重新排序:

$query = DB::table('users')->orderBy('name');

$usersOrderedByEmail = $query->reorder('email', 'desc')->get();

Grouping

groupBy & having 方法

如您所料,groupByhaving 方法用于将结果分组。 having 方法的使用与 where 方法十分相似:

$users = DB::table('users')
                ->groupBy('account_id')
                ->having('account_id', '>', 100)
                ->get();

你可以向 groupBy 方法传递多个参数,来对结果使用多个字段进行分组:

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

对于更高级的 having 语法,参见 havingRaw 方法。

Limit & Offset

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->input('role');

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

when 方法只有在第一个参数为 true 的时候才执行给的的闭包。如果第一个参数为 false ,那么这个闭包将不会被执行。因此,在上面的示例中,只有当传入请求中存在 role 字段并且计算结果为 true 时,才会调用传递给 when 方法的闭包。

你可以传递另一个闭包作为 when 方法的第三个参数。 该闭包会在第一个参数为 false 的情况下执行。为了说明如何使用这个特性,我们来配置一个查询的默认排序:

$sortByVotes = $request->input('sort_by_votes');

$users = DB::table('users')
                ->when($sortByVotes, function ($query, $sortByVotes) {
                    return $query->orderBy('votes');
                }, function ($query) {
                    return $query->orderBy('name');
                })
                ->get();

插入语句

查询构造器还提供了 insert 方法用于插入记录到数据库中。 insert 方法接收数组形式的字段名和字段值进行插入操作:

DB::table('users')->insert([
    'email' => 'kayla@example.com',
    'votes' => 0
]);

你甚至可以将二维数组传递给 insert 方法,依次将多个记录插入到表中:

DB::table('users')->insert([
    ['email' => 'picard@example.com', 'votes' => 0],
    ['email' => 'janeway@example.com', 'votes' => 0],
]);

insertOrIgnore 方法在将记录插入数据库时将忽略重复记录错误:

DB::table('users')->insertOrIgnore([
    ['id' => 1, 'email' => 'sisko@example.com'],
    ['id' => 2, 'email' => 'archer@example.com'],
]);

自增 IDs

如果数据表有自增 ID ,使用 insertGetId 方法来插入记录可以返回 ID 值:

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

注意:当使用 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 会尝试插入两条记录,如果记录存在与departuredestination 列相同的值,Laravel 将会更新 price 列的值。

注意:除 SQL Server 之外的所有数据库都要求 upsert 方法的第二个参数中的列具有 primaryunique 索引。

更新语句

当然, 除了插入记录到数据库中,查询构造器也可以通过 update 方法更新已有的记录。 update 方法和 insert 方法一样,接受包含要更新的字段及值的数组。你可以通过 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']
    );

更新 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']);

删除语句

查询构造器也可以使用 delete 方法从表中删除记录。 在使用 delete 前,可以添加 where 子句来约束 delete 语法:

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

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

您可以使用 truncate 方法来清空整个表,这将移除所有的数据并重置所有的自增 ID 为 0 :

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

清空表 & PostgreSQL

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

悲观锁

查询构造器也包含了一些能够帮助您在 select 语句中实现「悲观锁」的函数。要执行一个含有「共享锁」的语句,您可以在查询中使用 sharedLock 方法。共享锁可防止指定的数据列被篡改,直到事务被提交为止:

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

或者,您亦可使用 lockForUpdate 方法。使用「 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();

本文章首发在 LearnKu.com 网站上。

本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://learnku.com/docs/laravel/8.5/que...

译文地址:https://learnku.com/docs/laravel/8.5/que...

上一篇 下一篇
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
贡献者:16
讨论数量: 13
发起讨论 只看当前版本


kiyoma
多层次的条件判断如何用 when 来构造
1 个点赞 | 10 个回复 | 问答 | 课程版本 5.5
danguilangzi
whereJsonContains使用心得
1 个点赞 | 4 个回复 | 分享 | 课程版本 10.x
beyondxx3
如何跨数据库访问?
1 个点赞 | 3 个回复 | 问答 | 课程版本 5.5
shensu
miaotiao
关于 Laravel 文档的建议
0 个点赞 | 8 个回复 | 分享 | 课程版本 5.8
Janpun
Eloquent 如何查询具体时间
0 个点赞 | 4 个回复 | 问答 | 课程版本 5.5
wesen
having 方法与 where 的区别是什么?
0 个点赞 | 3 个回复 | 问答 | 课程版本 5.8
AmberLavigne
increment 和 decrement 添加条件使用的疑惑
0 个点赞 | 2 个回复 | 问答 | 课程版本 5.8
happyplay008
返回值
0 个点赞 | 2 个回复 | 问答 | 课程版本 5.5
zhizubaba
请问一下 JSON Where 语句 ->$[*] 这个 sql 怎么实现
0 个点赞 | 1 个回复 | 问答 | 课程版本 5.6
miaotiao
数据库查询构造器笔记——持续更新
0 个点赞 | 0 个回复 | 分享 | 课程版本 5.8
anuode
offset 自定义分页问题
0 个点赞 | 0 个回复 | 问答 | 课程版本 5.6