查询构造器


介绍

数据库查询构造器 (query builder) 提供方便流畅的接口来建立、执行数据库查询语法。在您的应用程序里面,它可以被使用在大部分的数据 库操作,而且它在所有支持的数据库系统上都可以执行。

注意: Laravel 查询构造器使用 PDO 参数绑定,以保护应用程序免于SQL注入攻击 (SQL injection),因此传入的参数不需过滤额外的特殊字符串。

Selects

从数据库表中取得所有的数据列

  1. $users = DB::table('users')->get();
  2. foreach ($users as $user)
  3. {
  4. var_dump($user->name);
  5. }

从数据库表中取得单一数据列

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

从数据库表中取得单一数据列的单一字段

  1. $name = DB::table('users')->where('name', 'John')->pluck('name');

取得单一字段值的列表

  1. $roles = DB::table('roles')->lists('title');

这个方法将会回传含有数据库表 role 的 title 字段值的数组。您也可以通过下面的方法,为回传的数组指定自定义键值。

  1. $roles = DB::table('roles')->lists('title', 'name');

指定查询子句 (Select Clause)

  1. $users = DB::table('users')->select('name', 'email')->get();
  2. $users = DB::table('users')->distinct()->get();
  3. $users = DB::table('users')->select('name as user_name')->get();

增加查询子句到现有的的查询中

  1. $query = DB::table('users')->select('name');
  2. $users = $query->addSelect('age')->get();

使用 where 及运算符

  1. $users = DB::table('users')->where('votes', '>', 100)->get();

"or" 语法

  1. $users = DB::table('users')
  2. ->where('votes', '>', 100)
  3. ->orWhere('name', 'John')
  4. ->get();

使用 Where Between

  1. $users = DB::table('users')
  2. ->whereBetween('votes', array(1, 100))->get();

使用 Where Not Between

  1. $users = DB::table('users')
  2. ->whereNotBetween('votes', array(1, 100))->get();

使用 Where In 与数组

  1. $users = DB::table('users')
  2. ->whereIn('id', array(1, 2, 3))->get();
  3. $users = DB::table('users')
  4. ->whereNotIn('id', array(1, 2, 3))->get();

使用 Where Null 找有未设定的值的数据

  1. $users = DB::table('users')
  2. ->whereNull('updated_at')->get();

排序(Order By), 分群(Group By), 及 Having

  1. $users = DB::table('users')
  2. ->orderBy('name', 'desc')
  3. ->groupBy('count')
  4. ->having('count', '>', 100)
  5. ->get();

偏移(Offset) 及 限制(Limit)

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

Joins

查询构造器也可以使用 join 语法,看看下面的例子:

基本的 Join 语法

  1. DB::table('users')
  2. ->join('contacts', 'users.id', '=', 'contacts.user_id')
  3. ->join('orders', 'users.id', '=', 'orders.user_id')
  4. ->select('users.id', 'contacts.phone', 'orders.price')
  5. ->get();

Left Join 语法

  1. DB::table('users')
  2. ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
  3. ->get();

您也可以指定更进阶的 join 子句

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

如果您想在您的 join 中使用 where 型式的子句,您可以在 join 子句里使用 whereorWhere 方法。下面的方法将会比较 contacts 数据库表中的 user_id 的字段值,而不是比较两个字段。

  1. DB::table('users')
  2. ->join('contacts', function($join)
  3. {
  4. $join->on('users.id', '=', 'contacts.user_id')
  5. ->where('contacts.user_id', '>', 5);
  6. })
  7. ->get();

进阶 Wheres

群组化参数

有些时候您需要更进阶的 where 子句,如 "where exists" 或多维数组参数。Laravel 的查询构造器也可以处理这样的情况;

  1. DB::table('users')
  2. ->where('name', '=', 'John')
  3. ->orWhere(function($query)
  4. {
  5. $query->where('votes', '>', 100)
  6. ->where('title', '<>', 'Admin');
  7. })
  8. ->get();

上面的查询语法会产生下方的 SQL:

  1. select * from users where name = 'John' or (votes > 100 and title <> 'Admin')

Exists 语法

  1. DB::table('users')
  2. ->whereExists(function($query)
  3. {
  4. $query->select(DB::raw(1))
  5. ->from('orders')
  6. ->whereRaw('orders.user_id = users.id');
  7. })
  8. ->get();

上面的查询语法会产生下方的 SQL:

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

聚合

查询构造器也提供各式各样的聚合方法,如 count, max, min, avgsum

使用聚合方法

  1. $users = DB::table('users')->count();
  2. $price = DB::table('orders')->max('price');
  3. $price = DB::table('orders')->min('price');
  4. $price = DB::table('orders')->avg('price');
  5. $total = DB::table('users')->sum('votes');

Raw Expressions

有些时候您需要使用 raw expression 在查询语句里,这样的表达式会成为字串插入至查询中,因此要小心勿建立任何 SQL 注入的攻击点。要建立 raw expression,您可以使用 DB::raw 方法:

使用 Raw Expression

  1. $users = DB::table('users')
  2. ->select(DB::raw('count(*) as user_count, status'))
  3. ->where('status', '<>', 1)
  4. ->groupBy('status')
  5. ->get();

新增

新增一条数据进数据库表

  1. DB::table('users')->insert(
  2. array('email' => 'john@example.com', 'votes' => 0)
  3. );

新增自动递增 (Auto-Incrementing) ID 的数据至数据库表

如果数据库表有自动递增的ID,可以使用 insertGetId 新增数据并回传该 ID:

  1. $id = DB::table('users')->insertGetId(
  2. array('email' => 'john@example.com', 'votes' => 0)
  3. );

注意: 当使用 PostgreSQL 时,insertGetId 方法会预先自动递增字段名为 "id" 的值。

新增多条数据进数据库表

  1. DB::table('users')->insert(array(
  2. array('email' => 'taylor@example.com', 'votes' => 0),
  3. array('email' => 'dayle@example.com', 'votes' => 0),
  4. ));

更新

更新数据库表中的数据

  1. DB::table('users')
  2. ->where('id', 1)
  3. ->update(array('votes' => 1));

对字段递增或递减数值

  1. DB::table('users')->increment('votes');
  2. DB::table('users')->increment('votes', 5);
  3. DB::table('users')->decrement('votes');
  4. DB::table('users')->decrement('votes', 5);

您也可以同时更新其他字段

  1. DB::table('users')->increment('votes', 1, array('name' => 'John'));

删除

删除数据库表中的数据

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

删除数据库表中的所有数据

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

清空数据库表

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

Unions

查询构造器也提供一个快速的方法去"合并 (union)"两个查询的结果:

  1. $first = DB::table('users')->whereNull('first_name');
  2. $users = DB::table('users')->whereNull('last_name')->union($first)->get();

unionAll 方法也可以使用,它与 union 方法的使用方式一样。

悲观锁定 (Pessimistic Locking)

查询构造器提供了少数函数协助您在 SELECT 语句中做到“悲观锁定”。

您只要在 SELECT 查询语句中使用 sharedLock

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

在 select 语法中,要"锁住更新(lock for update)",您仅需在查询语句中使用 lockForUpdate 方法即可:

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

缓存查询结果

使用 remember 方法,您可以轻松的缓存查询结果:

  1. $users = DB::table('users')->remember(10)->get();

这个例子中,查询结果将会缓存 10 分钟。当结果被缓存时,查询语句将不会被执行,而会从应用程序指定的缓存驱动器中载入缓存的结果。

如果您正在使用的是 支持标签的缓存驱动器,您也可以为缓存增加标签:

  1. $users = DB::table('users')->cacheTags(array('people', 'authors'))->remember(10)->get();