查询生成器


简介

查询生成器 为操作数据库提供了一个方便,顺畅的的接口,它支持所有Laravel支持的数据库系统,并能够完成绝大部分查询任务。

注意: 查询生成器 使用了PDO参数绑定传递的方式,从而避免sql注入攻击,也就是在使用参数时不需要进行保证安全性的过滤操作。

获取数据

获取一张表里的所有数据

$users = DB::table('users')->get();

  1. foreach ($users as $user)
  2. {
  3. var_dump($user->name);
  4. }

获取一张表里的一条数据

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

获取一张表里的满足where条件的第一行数据的指定字段的值

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

以列表形势获取一张表里一个字段的值

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

lists方法返回一个包含所有roles表的title字段的值的数组. 可以通过lists的第二个参数为返回的数组自定义键名:

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

筛选查询结果

  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语句中使用In子句,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();

使用whereNull方法获取未被清除或未被初始化的记录(字段如果没有指定默认值将会是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();

连接

查询生成器 也可以用来建立数据连接操作,我们看看下面的例子:

简单连接语句

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

左连接(Left Join)语句

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

指定更多的连接条件:

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

高级查询条件

有时你可能需要创建更高级的where查询,比如 "where exists"筛选 或者给where条件分组. 查询生成器 都能够很好的处理:

where条件分组

  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')

where中的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, avg,和 sum.

使用聚合方法

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

原始查询表达式

有时,你可能需要使用原始的查询表达式, 这种表达式需要直接插入最终的sql语句中, 所以,请特别注意防范sql注入! 使用 DB::raw 方法实现原始查询表达式:

使用原始查询表达式

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

将数据表中的某个字段+1或-1

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

创建数据

插入一条数据

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

如果数据表已经有主键了, 使用 insertGetId 方法插入数据,不需要主键字段信息:

同时插入多条数据,同时让主键自增

  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')->where('votes', '<', 100)->delete();

删除一张表的所有数据

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

清空一张表

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

union合并查询结果

查询生成器提供了一个快速的方式来 "union" 两个查询:

使用Union合并两次查询

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

unionAll 也是可用的, 它和 union 方法一样.

缓存查询结果

使用 remember 方法可以很容易的缓存查询结果:

缓存一次查询的查询结果

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

在上面的例子中, 查询结果将被缓存10分钟, 当某个查询的结果正在被缓存时, 该查询实际不会执行, 查询结果将直接从缓存系统中读取。

译者:苏小林 github