查询所有 $data = DB::table('user')->get(); 查询所有,并指定字段 推荐使第一种方式 $data = DB::table('user')->get(['name','age']); 查询单条数据 $ret = DB::table('member')->where('id', 5)->first(); 获取一列数据 $ret = DB::table('member')->pluck('name'); 分页操作 $ret = DB::table('member')->orderBy('id','desc')->offset(0)->limit(2)->get(); limit:表示限制输出的条数 offset:从什么地方开始,起始从0开始 排序 以ID来进行倒序排列 增删改查 $ret = DB::table('member')->orderBy('id','desc')->get(); insert() 可以同时添加一条或多条,返回值是布尔类型。 insertGetId() 只能添加一条数据,返回自增的id。 添加多条记录 $ret = DB::table('member')->insert([ ['name'=>'AAAA','age'=>20,'email'=>'111@111.com'], ['name'=>'BBBB','age'=>30,'email'=>'222@222.com'], ]); 添加数据并得到插入时的ID值 $ret = DB::table('member')->insertGetId([ 'name' => '小华', 'age' => 60, 'email' => 'ff@ff.com' ]); 修改 $ret = DB::table('member')->where('id', 2)->update([ 'name' => '修改一下', 'age' => 50 ]); 删除数据 $ret = DB::table('member')->where('id',2)->delete();
//批量更新 public function batchUpdateSql($multipleData = []) { if (empty($multipleData)) { return false; } $firstRow = current($multipleData); $updateColumn = array_keys($firstRow); // 默认以id为条件更新,如果没有ID则以第一个字段为条件 $referenceColumn = isset($firstRow['id']) ? 'id' : current($updateColumn); unset($updateColumn[0]); // 拼接sql语句 $updateSql = "UPDATE " . $this->table . " SET "; $sets = []; $bindings = []; foreach ($updateColumn as $uColumn) { $setSql = "`" . $uColumn . "` = CASE "; foreach ($multipleData as $data) { $setSql .= "WHEN `" . $referenceColumn . "` = ? THEN ? "; $bindings[] = $data[$referenceColumn]; $bindings[] = $data[$uColumn]; } $setSql .= "ELSE `" . $uColumn . "` END "; $sets[] = $setSql; } $updateSql .= implode(', ', $sets); $whereInData = collect($multipleData)->pluck($referenceColumn)->values()->all(); $whereIn = rtrim(str_repeat('?,', count($whereInData)), ','); $updateSql = rtrim($updateSql, ", ") . " WHERE `" . $referenceColumn . "` IN (" . $whereIn . ")"; $bindings = array_merge($bindings, $whereInData); // 传入预处理sql语句和对应绑定数据 return DB::update($updateSql, $bindings); }