Laravel 的数据库查询构造器为创建和运行数据库语句提供了一个方便而流畅的接口。它可用于执行应用中大部分数据库操作并在所有支持的数据库系统上运行。
Laravel 的查询构造器使用 PDO 参数绑定来保护应用免受 SQL 注入攻击。因此无需清理作为绑定被传递的字符串。
可以使用 DB Facade 的 table 方法创建语句。table 方法为给定数据表返回一个流畅的查询构造器,允许您在查询语句上链式调用更多约束,然后使用 get 方法获取结果:
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
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');如果要获取包含一列的所有值的集合,可以使用 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 方法。此方法一次只获取结果的一小块,并将每块数据传递到闭包中进行处理。此方法在编写处理上千条记录的 Artisan 命令 时非常有用。例如,我们将整个 users 表每次按 100 条记录进行分块:
DB::table('users')->orderBy('id')->chunk(100, function ($users) {
foreach ($users as $user) {
//
}
});也可以通过在闭包中处理完后返回 false 停止后续分块:
DB::table('users')->orderBy('id')->chunk(100, function ($users) {
// 处理记录
return false;
});由于经常会通过主键对结果进行分块,因此可以使用 chunkById 方法作为快捷用法:
DB::table('users')->chunkById(100, function ($users) {
foreach ($users as $user) {
//
}
});在分块回调中更新或删除记录时,对主键或外键的任何更改都可能会影响分块查询。可能导致记录不包含在分块结果中。
查询构造器也提供各种聚合方法,例如 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 方法,还可以使用下列方法在查询的各个地方插入原生表达式。
selectRawselectRaw 方法可用于代替 select(DB::raw(...))。此方法接收一个可选的数组绑定作为其第二个参数:
$orders = DB::table('orders')
->selectRaw('price * ? as price_with_tax', [1.0825])
->get();whereRaw/orWhereRawwhereRaw 和 orWhereRaw 方法可用于注入 where 语句到查询中。这些方法接收一个可选的数组绑定作为其第二个参数:
$orders = DB::table('orders')
->whereRaw('price > IF(state = "TX", ?, 100)', [200])
->get();havingRaw/orHavingRawhavingRaw 和 orHavingRaw 方法可用于设置原生字符串作为 having 语句的值。这些方法接收一个可选的数组绑定作为其第二个参数:
$orders = DB::table('orders')
->select('department', DB::raw('SUM(price) as total_sales'))
->groupBy('department')
->havingRaw('SUM(price) > ?', [2500])
->get();orderByRaworderByRaw 方法可用于设置原生字符串作为 order by 语句的值:
$orders = DB::table('orders')
->orderByRaw('updated_at - created_at DESC')
->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 方法。leftJoin 方法和 join 方法参数相同:
$users = DB::table('users')
->leftJoin('posts', 'users.id', '=', 'posts.user_id')
->get();要执行「交叉连接」,可以带上要交叉连接的表名使用 crossJoin 方法。交叉连接生成一个第一张表和连接表的笛卡尔乘积:
$users = DB::table('sizes')
->crossJoin('colours')
->get();也可以指定更高级的连接语句。将一个闭包作为第二个参数传递给 join 方法。闭包接收一个允许您指定 join 语句约束的 JoinClause 对象:
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 方法连接查询到子查询。每个方法都接收三个参数:子查询,表别名和定义相关字段的闭包:
$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 至少需要三个参数。第一个参数是字段名。第二个参数是一个操作符,可以是数据库支持的任何操作。最后,第三个参数值用来和字段值比较。
例如,这里有一个验证「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();可以在链式调用 where 语句时也在查询中添加 or 语句。orWhere 方法接收和 where 方法相同的参数:
$users = DB::table('users')
->where('votes', '>', 100)
->orWhere('name', 'John')
->get();whereBetween 方法验证字段值是否在给定的两个值之间:
$users = DB::table('users')
->whereBetween('votes', [1, 100])->get();whereNotBetween 方法验证字段值是否在两个值之外:
$users = DB::table('users')
->whereNotBetween('votes', [1, 100])
->get();whereIn 方法验证给定字段值是否包含在给定数组中:
$users = DB::table('users')
->whereIn('id', [1, 2, 3])
->get();whereNotIn 方法验证给定字段值是否 不 包含在给定数组中:
$users = DB::table('users')
->whereNotIn('id', [1, 2, 3])
->get();whereNull 方法验证给定字段的值是否为 NULL:
$users = DB::table('users')
->whereNull('updated_at')
->get();whereNotNull 方法验证给定字段的值是否不为 NULL:
$users = DB::table('users')
->whereNotNull('updated_at')
->get();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 方法可用于验证两个字段是否相等:
$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 的查询构造器可以很好的处理。我们看一个在括号中进行分组约束的示例:
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调用进行分组,以避免应用全局作用域时出现超出预期的行为。
whereExists 方法允许您编写 where exists SQL 语句。where exists 方法接收一个闭包参数,闭包接收一个定义「exists」查询语句的查询构造器实例:
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
)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 数组的长度查询 JSON 数组:
$users = DB::table('users')
->whereJsonLength('options->languages', 0)
->get();
$users = DB::table('users')
->whereJsonLength('options->languages', '>', 1)
->get();orderBy 方法允许您通过给定字段对查询结果进行排序。传递给 orderBy 方法的第一个参数是希望排序的字段,而第二个参数控制排序的方向,可以是 asc 或 desc:
$users = DB::table('users')
->orderBy('name', 'desc')
->get();latest 和 oldest 方法允许您通过日期对结果排序。默认情况下,结果会通过 created_at 字段进行排序。或者,可以传递希望排序的字段名:
$user = DB::table('users')
->latest()
->first();inRandomOrder 方法可用于对查询结果进行随机排序。例如,可以使用此方法获取一个随机用户:
$randomUser = DB::table('users')
->inRandomOrder()
->first();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 方法:
$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 时执行给定的闭包。如果第一个参数为 false,闭包将不会执行。
可以将另一个闭包作为第三个参数传递给 when 方法。此闭包会在第一个参数为 false 时执行。为了说明如何使用该功能,我们会使用它配置查询的默认排序:
$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]
);甚至还可以通过传递一个包含数组的数组,在一次调用中插入多条记录到数据表中。每个数组代表要插入到数据表的一行:
DB::table('users')->insert([
['email' => 'taylor@example.com', 'votes' => 0],
['email' => 'dayle@example.com', 'votes' => 0]
]);如果数据表有自增 ID,可以使用 insertGetId 方法在插入一条记录后获取 ID:
$id = DB::table('users')->insertGetId(
['email' => 'john@example.com', 'votes' => 0]
);使用 PostgreSQL 时,
insertGetId方法期望自增字段被命名为id。如果要从其它不同的「序列」获取 ID,可以将字段名作为第二个参数传递给insertGetId方法。
当然,除了插入记录到数据库,查询构造器还可以使用 update 方法更新已存在的记录。与 insert 方法一样,update方法接收一个包含要更新字段的字段名和字段值的数组。可以使用 where 语句约束 update 查询:
DB::table('users')
->where('id', 1)
->update(['votes' => 1]);更新 JSON 字段时,应该使用 -> 语法获取 JSON 对象对应的键。此操作仅支持 MySQL 5.7+:
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']);查询构造器也可通过 delete 方法从数据表中删除记录。可以在调用 delete 方法之前添加 where 语句来约束 delete 语句:
DB::table('users')->delete();
DB::table('users')->where('votes', '>', 100)->delete();如果要清空整个数据表,即删除所有行并将自增 ID 重置为 0,可以使用 truncate 方法:
DB::table('users')->truncate();查询构造器还包含一些函数帮助您在 select 语句上添加「悲观锁」。要运行一个带「共享锁」的语句,可以在查询上使用 sharedLock 方法。共享锁可以避免查询的行被修改直到事务提交:
DB::table('users')->where('votes', '>', 100)->sharedLock()->get();或者,可以使用 lockForUpdate 方法。「更新锁」可以避免行被修改或使用另一个共享锁查询:
DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();