总结之一 DB类

因为是使用查询构建器对数据库进行增删改查,所以以下都是相关的方法介绍:

一 新增数据

笔者喜欢的固定方法insertGetId(),插入记录后返回自增ID。

$insertId = DB::table('users')->insertGetId(
    ['name'=>'Laravel-Academy','email'=>'[email protected]','password'=>'456']
);

二 更新数据

更新表记录很简单,使用查询构建器的update方法,返回两种状态:1表示更新完成;0表示更新失败

$affected = DB::table('users')->where('name','Laravel-Academy')->update(['password'=>'123']);

update()方法里必须放的是数组形式。

三 删除数据

使用delete方法删除表记录,删除方法和更新方法类似,返回两种状态:1表示删除成功 0表示删除失败

$deleted = DB::table('users')->where('id', '>', 3)->delete();

ps:
如果我们是要删除整个数据表数据,则略去where条件,如果是要清空数据表还要将自增ID置为0,可以使用truncate方法:

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

四 查询

4.1 获取所有表记录

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

得到如下所示:

Collection {#345 ▼
  #items: array:48 [▼
    0 => {#346 ▼
      +"id": 1
      +"name": "已按期完成了前述超短期融资券的兑付"
      +"property": "1"
      +"score": 1
      +"version": 1.0
    }
    1 => {#347 ▶}
    2 => {#348 ▶}
    3 => {#349 ▶}

4.2 如果是获取指定列的数据,则需要加上select条件:

 $affected = DB::table('common_emotion')->select('name','score')->get();
 dd($affected);

得到如下所示:

Collection {#344 ▼
  #items: array:48 [▼
    0 => {#345 ▼
      +"name": "已按期完成了前述超短期融资券的兑付"
      +"score": 1
    }
    1 => {#347 ▼
      +"name": "固定收益类有所增加"
      +"score": 1
    }

4.3 获取单条记录需要在查询基础上加上first方法:

  $affected = DB::table('common_emotion')->first();
  dd($affected);

得到:

{#346 ▼
  +"id": 1
  +"name": "已按期完成了前述超短期融资券的兑付"
  +"property": "1"
  +"score": 1
  +"version": 1.0
}

五 事务

在涉及到多表操作时,为了保证数据的可靠性和统一性,我们可以加入事务处理

DB::beginTransaction();
try {

  
    DB::commit();

  } catch (Exception $e){

    DB::rollback();
    throw $e;

  }

六 高级操作

6.1 聚合函数 比如 count, max, min, avg, 和 sum

$users = DB::table('users')->count();
$price = DB::table('orders')->max('price');

6.2 where语句

$users = DB::table('users')->where('votes', '>', 100)->get(); //votes字段大于100 的所有结果集

$users = DB::table('users')->where('votes', 100)->get();//votes字段等于100的所有结果集

$users = DB::table('users')
                ->where('votes', '>=', 100)
                ->get();//votes字段大于等于100的所有结果集

$users = DB::table('users')
                ->where('votes', '<>', 100)
                ->get();//votes字段大于小于100的

$users = DB::table('users')
                ->where('name', 'like', 'T%')
                ->get();//模糊查询

6.3 你可以通过方法链将多个where约束链接到一起,也可以添加or子句到查询,orWhere方法和where方法接收参数一样:得到多个条件约束的并集

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

6.4 whereBetween方法验证列值是否在给定值之间:需要注意的是between里给的数组里面的值是有顺序的,是一个起始坐标值。例如下面:获取votes的值从1到100区间范围的所有结果集 不能写出[100,1]


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

6.5 whereNotBetween方法验证列值不在给定值之间:和6.3的情况一下。

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

6.6 whereIn方法验证给定列的值是否在给定数组中:这里的数组是没有顺序的 得到的是 id值在1,2,3中的所有结果集

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

6.7 whereNotIn方法验证给定列的值不在给定数组中:同6.5一样

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

七 排序 分组 限定

7.1 orderBy方法允许你通过给定列对结果集进行排序,orderBy的第一个参数应该是你希望排序的列,第二个参数控制着排序的方向——asc或desc:

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

7.2 groupBy和having方法用于对结果集进行分组,having方法和where方法的用法类似:

$users = DB::table('users')
                ->groupBy('account_id')
                ->having('account_id', '>', 100)
                ->get();

7.3 想要限定查询返回的结果集的数目,或者在查询中跳过给定数目的结果,可以使用skip和take方法:

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

7.4 限制获取条数

$users = DB::table('users')->limit(10)->get();
$users = DB::table('users')->offset(0)->limit(10)->get();

从第2个开始,获取10个

7.5 从数据库中获取单一数据列的单一字段 得到的结果

  $orientation=DB::table('data_yq_list')->where('kvUuid',$idtime[$i][0])->pluck("kvOrientation")->first();//会得到一个字符串  “2”

  $orientation=DB::table('data_yq_list')->where('kvUuid',$idtime[$i][0])->pluck("kvOrientation");//会得到一个 collection类

八 分页查询

8.1 查询时 paginate的唯一参数就是你每页想要显示的数目,这里我们指定每页显示15个:

  /**
     * 显示应用中的所有用户
     *
     * @return Response
     */
    public function index()
    {
        $users = DB::table('users')->where('votes', '>', 100)->paginate(15);
        return view('user.index', ['users' => $users]);
    }

前端视图如何获取?

@foreach ($users as $user) {{ $user->name }} @endforeach
{!! $users->links() !!}

links方法将会将结果集中的其它页面链接渲染出来。每个链接已经包含了?page查询字符串变量

8.2 添加参数到分页链接

你可以使用appends方法添加查询参数到分页链接查询字符串。例如,要添加&sort=votes到每个分页链接,应该像如下方式调用appends:

{!! $users->appends(['sort' => 'votes'])->links() !!}

8.3 更多辅助方法

$results->count()
$results->currentPage()
$results->firstItem()
$results->hasMorePages()
$results->lastItem()
$results->lastPage() (使用simplePaginate时无效)
$results->nextPageUrl()
$results->perPage()
$results->previousPageUrl()
$results->total() (使用simplePaginate时无效)
$results->url($page)

distinct()  允许你强制让查找返回不重复的结果:

http://www.cnblogs.com/redirect/p/6136190.html

你可能感兴趣的:(总结之一 DB类)