数据库:查询构建器
介绍
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 Response
*/
public function index()
{
$users = DB::table('users')->get();
return view('user.index', ['users' => $users]);
}
}
get
方法返回一个 Illuminate\Support\Collection
,其中包含结果,每个结果都是 PHP stdClass
对象的实例。您可以通过访问对象的属性来访问每个列的值:
foreach ($users as $user) {
echo $user->name;
}
从表中检索单行/列
如果只需要从数据库表中检索一行,可以使用 first
方法。此方法将返回一个 stdClass
对象:
$user = DB::table('users')->where('name', 'John')->first();
echo $user->name;
如果您甚至不需要整行,可以使用 value
方法从记录中提取单个值。此方法将直接返回列的值:
$email = DB::table('users')->where('name', 'John')->value('email');
要通过 id
列值检索单行,请使用 find
方法:
$user = DB::table('users')->find(3);
检索列值列表
如果希望检索包含单列值的集合,可以使用 pluck
方法。在此示例中,我们将检索角色标题的集合:
$titles = DB::table('roles')->pluck('title');
foreach ($titles as $title) {
echo $title;
}
您还可以为返回的集合指定自定义键列:
$roles = DB::table('roles')->pluck('title', 'name');
foreach ($roles as $name => $title) {
echo $title;
}
分块结果
如果需要处理数千条数据库记录,请考虑使用 chunk
方法。此方法一次检索一小块结果,并将每个块传递给 Closure
进行处理。此方法非常适合编写处理数千条记录的 Artisan 命令。例如,让我们以每次 100 条记录的块处理整个 users
表:
DB::table('users')->orderBy('id')->chunk(100, function ($users) {
foreach ($users as $user) {
//
}
});
您可以通过从 Closure
返回 false
来停止进一步的块处理:
DB::table('users')->orderBy('id')->chunk(100, function ($users) {
// 处理记录...
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
。您可以在构建查询后调用这些方法:
$users = DB::table('users')->count();
$price = DB::table('orders')->max('price');
您可以将这些方法与其他子句结合使用:
$price = DB::table('orders')
->where('finalized', 1)
->avg('price');
确定记录是否存在
与其使用 count
方法来确定是否存在匹配查询约束的记录,您可以使用 exists
和 doesntExist
方法:
return DB::table('orders')->where('finalized', 1)->exists();
return DB::table('orders')->where('finalized', 1)->doesntExist();
选择
指定选择子句
您可能并不总是希望从数据库表中选择所有列。使用 select
方法,您可以为查询指定自定义 select
子句:
$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
,您还可以使用以下方法将原始表达式插入查询的各个部分。
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
方法的第一个参数是需要连接的表的名称,而其余参数指定连接的列约束。您甚至可以在单个查询中连接多个表:
$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();
高级连接子句
您还可以指定更高级的连接子句。要开始,请将 Closure
作为第二个参数传递给 join
方法。Closure
将接收一个 JoinClause
对象,允许您在 join
子句上指定约束:
DB::table('users')
->join('contacts', function ($join) {
$join->on('users.id', '=', 'contacts.user_id')->orOn(...);
})
->get();
如果希望在连接上使用 "where" 样式的子句,可以在连接上使用 where
和 orWhere
方法。这些方法将比较列与值,而不是比较两个列:
DB::table('users')
->join('contacts', function ($join) {
$join->on('users.id', '=', 'contacts.user_id')
->where('contacts.user_id', '>', 5);
})
->get();
子查询连接
您可以使用 joinSub
、leftJoinSub
和 rightJoinSub
方法将查询连接到子查询。每个方法接收三个参数:子查询、其表别名和定义相关列的 Closure:
$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();
联合
查询构建器还提供了一种快速的方法来将两个查询 "联合" 在一起。例如,您可以创建一个初始查询,并使用 union
方法将其与第二个查询联合:
$first = DB::table('users')
->whereNull('first_name');
$users = DB::table('users')
->whereNull('last_name')
->union($first)
->get();
unionAll
方法也可用,其方法签名与 union
相同。
Where 子句
简单的 Where 子句
您可以在查询构建器实例上使用 where
方法向查询添加 where
子句。对 where
的最基本调用需要三个参数。第一个参数是列的名称。第二个参数是运算符,可以是数据库支持的任何运算符。最后,第三个参数是要与列进行比较的值。
例如,以下是一个验证 "votes" 列的值是否等于 100 的查询:
$users = DB::table('users')->where('votes', '=', 100)->get();
为了方便起见,如果要验证列是否等于给定值,可以将值直接作为 where
方法的第二个参数传递:
$users = DB::table('users')->where('votes', 100)->get();
您可以在编写 where
子句时使用多种其他运算符:
$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
函数:
$users = DB::table('users')->where([
['status', '=', '1'],
['subscribed', '<>', '1'],
])->get();
Or 语句
您可以将 where 约束链接在一起,并向查询添加 or
子句。orWhere
方法接受与 where
方法相同的参数:
$users = DB::table('users')
->where('votes', '>', 100)
->orWhere('name', 'John')
->get();
如果需要在括号内分组 "or" 条件,可以将 Closure 作为 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)
其他 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();
您还可以将比较运算符传递给方法:
$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 子句,例如 "where exists" 子句或嵌套参数分组。Laravel 查询构建器也可以处理这些。首先,让我们看一个在括号内分组约束的示例:
$users = DB::table('users')
->where('name', '=', 'John')
->where(function ($query) {
$query->where('votes', '>', 100)
->orWhere('title', '=', 'Admin');
})
->get();
如您所见,将 Closure
传递给 where
方法指示查询构建器开始一个约束组。Closure
将接收一个查询构建器实例,您可以使用它来设置应包含在括号组中的约束。上面的示例将生成以下 SQL:
select * from users where name = 'John' and (votes > 100 or title = 'Admin')
您应始终对 orWhere
调用进行分组,以避免在应用全局作用域时出现意外行为。
Where Exists 子句
whereExists
方法允许您编写 where exists
SQL 子句。whereExists
方法接受一个 Closure
参数,该参数将接收一个查询构建器实例,允许您定义应放置在 "exists" 子句中的查询:
$users = DB::table('users')
->whereExists(function ($query) {
$query->select(DB::raw(1))
->from('orders')
->whereRaw('orders.user_id = users.id');
})
->get();
上面的查询将生成以下 SQL:
select * from users
where exists (
select 1 from orders where orders.user_id = users.id
)
子查询 Where 子句
有时您可能需要构建一个 where 子句,将子查询的结果与给定值进行比较。您可以通过将 Closure 和一个值传递给 where
方法来实现这一点。例如,以下查询将检索所有具有给定类型的最近 "membership" 的用户:
use App\User;
$users = User::where(function ($query) {
$query->select('type')
->from('membership')
->whereColumn('user_id', 'users.id')
->orderByDesc('start_date')
->limit(1);
}, 'Pro')->get();
JSON Where 子句
Laravel 还支持在支持 JSON 列类型的数据库上查询 JSON 列。目前,这包括 MySQL 5.7、PostgreSQL、SQL Server 2016 和 SQLite 3.9.0(带有 JSON1 扩展)。要查询 JSON 列,请使用 ->
运算符:
$users = DB::table('users')
->where('options->language', 'en')
->get();
$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();
排序、分组、限制与偏移
orderBy
orderBy
方法允许您按给定列对查询结果进行排序。orderBy
方法的第一个参数应为要排序的列,而第二个参数控制排序方向,可以是 asc
或 desc
:
$users = DB::table('users')
->orderBy('name', 'desc')
->get();
如果需要按多个列排序,可以根据需要多次调用 orderBy
:
$users = DB::table('users')
->orderBy('name', 'desc')
->orderBy('email', 'asc')
->get();
latest / oldest
latest
和 oldest
方法允许您轻松按日期排序结果。默认情况下,结果将按 created_at
列排序。或者,您可以传递要排序的列名:
$user = DB::table('users')
->latest()
->first();
inRandomOrder
inRandomOrder
方法可用于随机排序查询结果。例如,您可以使用此方法获取随机用户:
$randomUser = DB::table('users')
->inRandomOrder()
->first();
reorder
reorder
方法允许您删除所有现有的排序,并可选地应用新的排序。例如,您可以删除所有现有的排序:
$query = DB::table('users')->orderBy('name');
$unorderedUsers = $query->reorder()->get();
要删除所有现有的排序并应用新的排序,请将列和方向作为参数提供给方法:
$query = DB::table('users')->orderBy('name');
$usersOrderedByEmail = $query->reorder('email', 'desc')->get();
groupBy / having
groupBy
和 having
方法可用于对查询结果进行分组。having
方法的签名与 where
方法类似:
$users = DB::table('users')
->groupBy('account_id')
->having('account_id', '>', 100)
->get();
您可以将多个参数传递给 groupBy
方法,以按多个列进行分组:
$users = DB::table('users')
->groupBy('first_name', 'status')
->having('account_id', '>', 100)
->get();
有关更高级的 having
语句,请参见 havingRaw
方法。
skip / take
要限制查询返回的结果数量,或在查询中跳过给定数量的结果,可以使用 skip
和 take
方法:
$users = DB::table('users')->skip(10)->take(5)->get();
或者,您可以使用 limit
和 offset
方法:
$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
时执行给定的 Closure。如果第一个参数为 false
,则不会执行 Closure。
您可以将另一个 Closure 作为第三个参数传递给 when
方法。如果第一个参数计算为 false
,则将执行此 Closure。为了说明如何使用此功能,我们将使用它来配置查询的默认排序:
$sortBy = null;
$users = DB::table('users')
->when($sortBy, function ($query, $sortBy) {
return $query->orderBy($sortBy);
}, function ($query) {
return $query->orderBy('name');
})
->get();
插入
查询构建器还提供了一个 insert
方法,用于将记录插入数据库表。insert
方法接受一个包含列名和值的数组:
DB::table('users')->insert(
['email' => 'john@example.com', 'votes' => 0]
);
您甚至可以通过传递数组的数组来在单次调用 insert
时插入多条记录。每个数组代表要插入表中的一行:
DB::table('users')->insert([
['email' => 'taylor@example.com', 'votes' => 0],
['email' => 'dayle@example.com', 'votes' => 0],
]);
insertOrIgnore
方法将在将记录插入数据库时忽略重复记录错误:
DB::table('users')->insertOrIgnore([
['id' => 1, 'email' => 'taylor@example.com'],
['id' => 2, 'email' => 'dayle@example.com'],
]);
自动递增 ID
如果表具有自动递增的 id,请使用 insertGetId
方法插入记录,然后检索 ID:
$id = DB::table('users')->insertGetId(
['email' => 'john@example.com', 'votes' => 0]
);
使用 PostgreSQL 时,insertGetId
方法期望自动递增列名为 id
。如果希望从不同的 "序列" 中检索 ID,可以将列名作为第二个参数传递给 insertGetId
方法。
更新
除了将记录插入数据库外,查询构建器还可以使用 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]);
增量与减量
查询构建器还提供了方便的方法来增加或减少给定列的值。这是一个快捷方式,提供了比手动编写 update
语句更具表现力和简洁的接口。
这两种方法都至少接受一个参数:要修改的列。可以选择传递第二个参数来控制列应增加或减少的数量:
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']);
使用 increment
和 decrement
方法时不会触发模型事件。
删除
查询构建器还可以通过 delete
方法从表中删除记录。您可以在调用 delete
方法之前添加 where
子句来约束 delete
语句:
DB::table('users')->delete();
DB::table('users')->where('votes', '>', 100)->delete();
如果希望截断整个表,这将删除所有行并将自动递增 ID 重置为零,可以使用 truncate
方法:
DB::table('users')->truncate();
悲观锁定
查询构建器还包括一些函数,帮助您在 select
语句上进行 "悲观锁定"。要使用 "共享锁" 运行语句,可以在查询上使用 sharedLock
方法。共享锁会阻止选定的行在事务提交之前被修改:
DB::table('users')->where('votes', '>', 100)->sharedLock()->get();
或者,您可以使用 lockForUpdate
方法。"for update" 锁定会阻止行被修改或与另一个共享锁一起选择:
DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();
调试
您可以在构建查询时使用 dd
或 dump
方法来转储查询绑定和 SQL。dd
方法将显示调试信息,然后停止执行请求。dump
方法将显示调试信息,但允许请求继续执行:
DB::table('users')->where('votes', '>', 100)->dd();
DB::table('users')->where('votes', '>', 100)->dump();