查询构建器
介绍
数据库查询构建器提供了一个方便、流畅的接口来创建和运行数据库查询。它可以用于执行应用程序中的大多数数据库操作,并且适用于所有支持的数据库系统。
Laravel 查询构建器在整个过程中使用 PDO 参数绑定,以保护您的应用程序免受 SQL 注入攻击。传递作为绑定的字符串无需清理。
选择
从表中检索所有行
$users = DB::table('users')->get();
foreach ($users as $user)
{
var_dump($user->name);
}
从表中检索单行
$user = DB::table('users')->where('name', 'John')->first();
var_dump($user->name);
从行中检索单列
$name = DB::table('users')->where('name', 'John')->pluck('name');
检索列值列表
$roles = DB::table('roles')->lists('title');
此方法将返回角色标题的数组。您还可以为返回的数组指定自定义键列:
$roles = DB::table('roles')->lists('title', 'name');
指定选择子句
$users = DB::table('users')->select('name', 'email')->get();
$users = DB::table('users')->distinct()->get();
$users = DB::table('users')->select('name as user_name')->get();
向现有查询添加选择子句
$query = DB::table('users')->select('name');
$users = $query->addSelect('age')->get();
使用 Where 运算符
$users = DB::table('users')->where('votes', '>', 100)->get();
或语句
$users = DB::table('users')
->where('votes', '>', 100)
->orWhere('name', 'John')
->get();
使用 Between 条件
$users = DB::table('users')
->whereBetween('votes', array(1, 100))->get();
使用 Not Between 条件
$users = DB::table('users')
->whereNotBetween('votes', array(1, 100))->get();
使用 In 条件与数组
$users = DB::table('users')
->whereIn('id', array(1, 2, 3))->get();
$users = DB::table('users')
->whereNotIn('id', array(1, 2, 3))->get();
使用 Null 条件查找未设置值的记录
$users = DB::table('users')
->whereNull('updated_at')->get();
排序、分组和 Having
$users = DB::table('users')
->orderBy('name', 'desc')
->groupBy('count')
->having('count', '>', 100)
->get();
偏移和限制
$users = DB::table('users')->skip(10)->take(5)->get();
连接
查询构建器也可以用于编写连接语句。请查看以下示例:
基本连接语句
DB::table('users')
->join('contacts', 'users.id', '=', 'contacts.user_id')
->join('orders', 'users.id', '=', 'orders.user_id')
->select('users.id', 'contacts.phone', 'orders.price')
->get();
左连接语句
DB::table('users')
->leftJoin('posts', 'users.id', '=', 'posts.user_id')
->get();
您还可以指定更高级的连接子句:
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();
高级条件
参数分组
有时您可能需要创建更高级的条件子句,例如“where exists”或嵌套参数分组。Laravel 查询构建器也可以处理这些:
DB::table('users')
->where('name', '=', 'John')
->orWhere(function($query)
{
$query->where('votes', '>', 100)
->where('title', '<>', 'Admin');
})
->get();
上述查询将生成以下 SQL:
select * from users where name = 'John' or (votes > 100 and title <> 'Admin')
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
)
聚合
查询构建器还提供了多种聚合方法,例如 count
、max
、min
、avg
和 sum
。
使用聚合方法
$users = DB::table('users')->count();
$price = DB::table('orders')->max('price');
$price = DB::table('orders')->min('price');
$price = DB::table('orders')->avg('price');
$total = DB::table('users')->sum('votes');
原始表达式
有时您可能需要在查询中使用原始表达式。这些表达式将作为字符串注入到查询中,因此请小心不要创建任何 SQL 注入点!要创建原始表达式,您可以使用 DB::raw
方法:
使用原始表达式
$users = DB::table('users')
->select(DB::raw('count(*) as user_count, status'))
->where('status', '<>', 1)
->groupBy('status')
->get();
插入
向表中插入记录
DB::table('users')->insert(
array('email' => 'john@example.com', 'votes' => 0)
);
向具有自增 ID 的表中插入记录
如果表具有自增 ID,请使用 insertGetId
插入记录并检索 ID:
$id = DB::table('users')->insertGetId(
array('email' => 'john@example.com', 'votes' => 0)
);
使用 PostgreSQL 时,insertGetId 方法期望自增列名为“id”。
向表中插入多条记录
DB::table('users')->insert(array(
array('email' => 'taylor@example.com', 'votes' => 0),
array('email' => 'dayle@example.com', 'votes' => 0),
));
更新
更新表中的记录
DB::table('users')
->where('id', 1)
->update(array('votes' => 1));
增加或减少列的值
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, array('name' => 'John'));
删除
删除表中的记录
DB::table('users')->where('votes', '<', 100)->delete();
从表中删除所有记录
DB::table('users')->delete();
清空表
DB::table('users')->truncate();
联合
查询构建器还提供了一种快速“联合”两个查询的方法:
$first = DB::table('users')->whereNull('first_name');
$users = DB::table('users')->whereNull('last_name')->union($first)->get();
unionAll
方法也可用,并且具有与 union
相同的方法签名。
悲观锁定
查询构建器包含一些函数,以帮助您在 SELECT 语句上执行“悲观锁定”。
要使用“共享锁”运行 SELECT 语句,您可以在查询上使用 sharedLock
方法:
DB::table('users')->where('votes', '>', 100)->sharedLock()->get();
要在 SELECT 语句上“锁定以进行更新”,您可以在查询上使用 lockForUpdate
方法:
DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();
缓存查询
您可以使用 remember
或 rememberForever
方法轻松缓存查询结果:
$users = DB::table('users')->remember(10)->get();
在此示例中,查询的结果将缓存十分钟。在结果被缓存期间,查询将不会在数据库中运行,结果将从为您的应用程序指定的默认缓存驱动程序加载。
如果您使用的是支持的缓存驱动程序,您还可以向缓存添加标签:
$users = DB::table('users')->cacheTags(array('people', 'authors'))->remember(10)->get();