Query Builder cheatsheet

Query Builder cheatsheet

  1. simple operation
        $users = DB::select('select * from user where id = ?', [$id]);
DB::insert('insert into user (username, password) values (?, ?)', ['pikachu', '334455']);
// 会返回受影响的行数
$rows = DB::update('update user set password = ? where id = ?', ['222', 2]);
// 会返回受影响的行数
$rows = DB::delete('delete from user where id = ?', [3]);
使用 DB::statement 可以执行一些通用语句,比如下面删除整个 user 表:
DB::statement('drop table user');

2. database transaction

(1)在 transaction 闭包中的任何异常都会导致事务自动回滚:
DB::transaction(function()
{
    DB::update('update user set password = ? where id = ?', ['23', 2]);
    DB::delete('delete from user where id = ?', [3]);
});
(2)我们也可以手动控制事务的开启、回滚、提交:
// 开启事务
DB::beginTransaction();
 
// 回滚事务
DB::rollback();
 
// 提交事务
DB::commit();
3. multiple database connections
(1)当使用多个数据库连接时,可以通过 DB::connection 方法访问它们:
$users = DB::connection('foo')->select(...);
(2)我们可以通过 PDO 实例访问原生连接:
$pdo = DB::connection()->getPdo();
(3)如果需要重连数据库可以通过如下方法:
DB::reconnect('foo');
(4)如果因为超出 PDO 实例的最大连接数限制而要断开连接,使用 disconnect 方法:
DB::disconnect('foo');

4. on table() operations

insert(array(...)):接收包含字段名和值的数组,插入数据至数据库
find($id):检索一个主键 id 等于给定参数的记录
update(array(...)):接收含有字段名和值的数组,更新已存在的记录
delete():删除一条记录
get():返回一个 Illuminate\Support\Collection 结果,其中每个结果都是一个 PHP StdClass 对象的实例,实例中包含每行记录中的列名及其值
take($number):限制查询结果数量
......

查询

(1)返回某张表的所有记录(所有列)
$users = DB::table('user')->get();
//foreach ($users as $user) {
  //var_dump($user->username);
//}

(2)返回某张表的所有记录(指定列) 
$users = DB::table('user')->get(['id','username']);

(3)返回第一条记录
$users = DB::table('user')->first();

根据主键id查询数据

使用 find 操作符号可以检索一个主键 id 等于给定参数的记录。
// 下面相当于 select * from user where id = 2
$users = DB::table('user')->find(2);

使用 pluck 操作符可从数据表中取得单一数据列的单一字段(返回结果是一个数组)
$users = DB::table('user')
            ->pluck('username');

avg()、sum()、count()、min()、max() 等聚集函数
// 获取平均值
$result = DB::table('user')
            ->avg('id');
             
// 获取总和
$result = DB::table('user')
            ->sum('id');
 
// 获取总数
$result = DB::table('user')
            ->count();
             
// 获取最小值
$result = DB::table('user')
            ->min('id');
             
// 获取最大值
$result = DB::table('user')
            ->max('id');

### pagination/limit
(1)下面查询前 10 条记录
$users = DB::table('user')->take(10)->get();

(2)下面查询第 11 到 20 条记录
$users = DB::table('user')->skip(10)->take(10)->get();

### 排序 sequence , orderBy
(1)Query Builder 的 orderBy 操作符提供了一种简单的方法来对从数据库检索的数据进行排序。
$users = DB::table('user')
            ->orderBy('id', 'desc')
            ->get();
(2)orderBy 操作符是可链接的,可以组合多个 orderBy 以获取需要实现的排序结果。
$users = DB::table('user')
            ->orderBy('id', 'desc')
            ->orderBy('username', 'asc')
            ->get();

### 分组 groupBy
(1)groupBy 操作符类似于 SQL 中 GROUP BY 子句, 它只接受一个参数:用于对记录进行分组的列。
$users = DB::table('user')
            ->groupBy('id')
            ->get();
(2)可以结合 having 操作符使用:
$users = DB::table('user')
            ->groupBy('id')
            ->having('id', '>=', 2)
            ->get();

当同时含有where子句、group by 子句 、having子句及聚集函数时,执行顺序如下:
执行where子句查找符合条件的数据;
使用group by 子句对数据进行分组;对group by 子句形成的组运行聚集函数计算每一组的值;
最后用having 子句去掉不符合条件的组。
如果被 SELECT 的只有函數欄, 那就不需要 GROUP BY 子句。
SELECT "欄位1", SUM("欄位2") 
FROM "表格名" 
GROUP BY "欄位1" 
HAVING (函數條件);

select dno,count(*)
from employee
group by dno
having count(*)>3
需要注意:
having 子句中的每一个元素也必须出现在select列表中。有些数据库例外,如oracle.
having子句和where子句都可以用来设定限制条件以使查询结果满足一定的条件限制。
having子句限制的是组,而不是行。where子句中不能使用聚集函数,而having子句中可以。

## 过滤 filter
(1)where 的查询由提供用于过滤数据的三个参数组成:
(用于比较的列名,用于比较的运算符,用于比较的值)
支持的运算符如下:
=:等于
<:小于
>:大于
<=:小于等于
>=:大于等于
!=:不等于
like:模糊查询
not like:模糊查询

(2) 多个 where 链接表示 and 过滤
$users = DB::table('user')
            ->where('username', 'like','l%')
            ->where('id','<' ,50)
            ->get();

(3)orwhere 操作符表示 or 过滤。
$users = DB::table('user')
            ->where('username', 'like','l%')
            ->orwhere('id','<' ,50)
            ->get();

(4)whereBetween 操作符可以指定范围进行过滤,即数据在 [min, max] 范围中(包括 min 和 max)
$users = DB::table('user')
            ->whereBetween('id', [1,2])
            ->get();

(5)whereNotBetween 与上面刚好相反,即数据不在 [min, max] 范围中
$users = DB::table('user')
            ->whereNotBetween('id', [1,2])
            ->get();

(6)whereIn 与 whereNotIn 操作符表示数据是否在指定的数组集合中。
$users = DB::table('user')
            ->whereIn('id', array(1, 2, 3))
            ->get();
             
$users = DB::table('user')
            ->whereNotIn('id', array(1, 2, 3))
            ->get();

(7)whereNull 操作符可以过滤出某字段为空的记录。
$users = DB::table('user')
            ->whereNull('password')
            ->get();

(8)通过嵌套参数分组实现更复杂的 where 语句。
DB::table('users')

    ->where('name', '=', 'John')

    ->orWhere(function($query)
{

      $query->where('votes', '>', 100)

            ->where('title', '<>', 'Admin');

    })
    
->get();

(9) 指定一个 Select 子句对查询结果进行过滤
// 只返回 username、password 这两个字段数据
$users = DB::table('user')->select('username', 'password')->get();
 
// 只返回 username 字段数据,且别名变成 name
$users = DB::table('user')->select('username as name')->get();
 
// 只返回不重复的记录
$users = DB::table('user')->distinct()->get();

Multiple tables 关联表查询 join

(1)使用 join 操作符可以进行多表内连接:
// 连接 users、contacts、orders 这三个表
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();

(2)使 leftJoin 操作符可以进行左连接:
DB::table('users')
  ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
  ->get();

(3)通过嵌套参数分组实现更复杂的连接语句。
DB::table('users')
  ->join('contacts', function($join)
  {
   $join->on('users.id', '=', 'contacts.user_id')->orOn(...);
  })
  ->get();
  
DB::table('users')
  ->join('contacts', function($join)
  {
   $join->on('users.id', '=', 'contacts.user_id')
        ->where('contacts.user_id', '>', 5);
  })
  ->get();

插入

(1)插入单条纪录
DB::table('user')->insert(
  [
    'username' => 'guest',
    'password' => 'abc123',
  ]
);

(2)插入多条纪录
DB::table('user')->insert(
  [
    ['username' => 'guest1', 'password' => 'abc111'],
    ['username' => 'guest2', 'password' => 'abc222'],
    ['username' => 'guest3', 'password' => 'abc333']
  ]
);

 更新/修改

(1)更新所有的记录
DB::table('user')->update(['username'=>'newname']);

(2)更新符合条件的j记录。
DB::table('user')
    ->where('id','>','50')
    ->update(['username'=>'newname']);

删除

(1)删除所有记录
DB::table('user')->delete();

(2)删除符合条件的j记录。
DB::table('user')
    ->where('id','>','50')
    ->delete();

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.