[关闭]
@Chiang 2019-12-13T16:12:45.000000Z 字数 6698 阅读 503

数据库-查询构造器

Laravel


从数据表中获取所有的数据

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

从数据表中获取一行数据

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

从数据表中获取一行中的单独字段

  1. $users = DB::table('users')->where('name','john')->value('email');

获取一列的值

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

获取一列的值并指定键名

第二个参数为键名

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

结果分块

如果你需要操作数千条数据库记录,可以考虑使用 chunk 方法。这个方法每次只取出一小块结果,并会将每个块传递给一个 闭包 处理。这个方法对于编写数千条记录的 Artisan 命令 是非常有用的。例如,让我们把 users 表进行分块,每次操作 100 条数据

  1. DB::table('users')->orderBy('id')->chunk(100,function($users){
  2. foreach($users as $user){
  3. //...
  4. }
  5. });
  6. // 你可以从 闭包 中返回 false,以停止对后续分块的处理
  7. DB::table('users')->orderBy('id')->chunk(100, function ($users) {
  8. // Process the records...
  9. return false;
  10. });

聚合方法

  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')->sum('price');
  5. $price = DB::table('orders')->where('finalized', 1)->avg('price');

select distinct addSelect

  1. $users = DB::table('users')->select('name', 'email as user_email')->get();
  2. // 返回不重复的结果
  3. $users = DB::table('users')->distinct()->get();
  4. // 添加查询字段
  5. $query = DB::table('users')->select('name');
  6. $users = $query->addSelect('age')->get();

原始表达式 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();

inner join

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

left join

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

cross join

  1. $users = DB::table('sizes')
  2. ->crossJoin('colours')
  3. ->get();

join 子句

  1. DB::table('users')
  2. ->join('contacts', function ($join) {
  3. $join->on('users.id', '=', 'contacts.user_id')->orOn(...);
  4. })
  5. ->get();
  6. // 添加where
  7. DB::table('users')
  8. ->join('contacts', function ($join) {
  9. $join->on('users.id', '=', 'contacts.user_id')
  10. ->where('contacts.user_id', '>', 5);
  11. })
  12. ->get();

union unionAll

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

where

  1. $users = DB::table('users')->where('votes', '=', 100)->get();
  2. $users = DB::table('users')->where('votes', 100)->get();
  3. $users = DB::table('users')->where('votes', '>=', 100)->get();
  4. $users = DB::table('users')->where('votes', '<>', 100)->get();
  5. $users = DB::table('users')->where('name', 'like', 'T%')->get();
  6. $users = DB::table('users')->where([
  7. ['status', '=', '1'],
  8. ['subscribed', '<>', '1'],
  9. ])->get();

orWhere

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

whereBetween

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

whereNotBetween

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

whereIn

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

whereNotIn

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

whereNull

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

whereNotNull

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

whereDate

  1. $users = DB::table('users')
  2. ->whereDate('created_at', '2016-12-31')
  3. ->get();

whereMonth

  1. $users = DB::table('users')
  2. ->whereMonth('created_at', '12')
  3. ->get();

whereDay

  1. $users = DB::table('users')
  2. ->whereDay('created_at', '31')
  3. ->get();

whereYear

  1. $users = DB::table('users')
  2. ->whereYear('created_at', '2016')
  3. ->get();

whereColumn

  1. $users = DB::table('users')
  2. ->whereColumn('first_name', 'last_name')
  3. ->get();
  4. $users = DB::table('users')
  5. ->whereColumn('updated_at', '>', 'created_at')
  6. ->get();
  7. $users = DB::table('users')
  8. ->whereColumn([
  9. ['first_name', '=', 'last_name'],
  10. ['updated_at', '>', 'created_at']
  11. ])->get();

where 参数分组

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

Where Exists 语法

  1. DB::table('users')
  2. ->whereExists(function ($query) {
  3. $query->select(DB::raw(1))
  4. ->from('orders')
  5. ->whereRaw('orders.user_id = users.id');
  6. })
  7. ->get();
  8. // 生成的原生sql是
  9. select * from users
  10. where exists (
  11. select 1 from orders where orders.user_id = users.id
  12. )

JSON 查询语句

本特性仅支持 MySQL 5.7+ 和 Postgres数据库

  1. $users = DB::table('users')
  2. ->where('options->language', 'en')
  3. ->get();
  4. $users = DB::table('users')
  5. ->where('preferences->dining->meal', 'salad')
  6. ->get();

orderBy

  1. $users = DB::table('users')
  2. ->orderBy('name', 'desc')
  3. ->get();

latest / oldest

latest 和 oldest 方法允许你更容易的依据日期对查询结果排序。默认查询结果将依据 created_at 列

  1. $user = DB::table('users')->latest()->first();

inRandomOrder

inRandomOrder 方法可以将查询结果随机排序。例如,你可以使用这个方法获取一个随机用户

  1. $randomUser = DB::table('users')
  2. ->inRandomOrder()
  3. ->first();

groupBy / having / havingRaw

  • groupBy 和 having 方法可用来对查询结果进行分组。having 方法的用法和 where 方法类似
  • havingRaw 方法可以将一个原始的表达式设置为 having 子句的值
  1. $users = DB::table('users')
  2. ->groupBy('account_id')
  3. ->having('account_id', '>', 100)
  4. ->get();
  5. $users = DB::table('orders')
  6. ->select('department', DB::raw('SUM(price) as total_sales'))
  7. ->groupBy('department')
  8. ->havingRaw('SUM(price) > 2500')
  9. ->get();

skip / take

你可以使用 skip 和 take 方法来限制查询结果数量或略过指定数量的查询

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

条件语句 when

有时候,你希望某个值为 true 时才执行查询。例如,如果在传入请求中存在指定的输入值的时候才执行这个 where 语句。你可以使用 when 方法实现

  1. $role = $request->input('role');
  2. $users = DB::table('users')
  3. ->when($role, function ($query) use ($role) {
  4. return $query->where('role_id', $role);
  5. })
  6. ->get();
  1. $sortBy = null;
  2. $users = DB::table('users')
  3. ->when($sortBy, function ($query) use ($sortBy) {
  4. return $query->orderBy($sortBy);
  5. }, function ($query) {
  6. return $query->orderBy('name');
  7. })
  8. ->get();

insert

  1. DB::table('users')->insert(
  2. ['email' => 'john@example.com', 'votes' => 0]
  3. );
  4. DB::table('users')->insert([
  5. ['email' => 'taylor@example.com', 'votes' => 0],
  6. ['email' => 'dayle@example.com', 'votes' => 0]
  7. ]);

update

  1. DB::table('users')->where('id', 1)->update(['votes' => 1]);
  2. // 更新json
  3. DB::table('users')->where('id', 1)->update(['options->enabled' => true]);

自增或自减increment decrement

  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);
  5. // 附带更新其他字段
  6. DB::table('users')->increment('votes', 1, ['name' => 'John']);

delete

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

truncate

如果你需要清空表,你可以使用 truncate 方法,这将删除所有行,并重置自动递增 ID 为零

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

sharedLock

共享锁可防止选中的数据列被篡改,直到事务被提交为止

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

lockForUpdate

使用「更新」锁可避免行被其它共享锁修改或选取

  1. DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注