swoft 学习笔记之数据库操作
查询数据
- 查询一条数据,返回数据是一个实体或者null
$id = $request->input('id',0); $res = Saying::find($id,['content','type']); $res = Saying::where('id',$id)->select('content','type')->first();
- 查询多条数据,返回的是实体集合,如果没找到则为空集合,toArray之后,转换成二维数组或者一维空数组
$ids = [1,2,3]; $res = Saying::findMany($ids,['content','type']); $res = Saying::whereIn('id',$ids)->select('content','type')->get();
- 获取记录中的单个值
$content = Saying::where('id',1)->value('content');
插入数据
- 对象方式
$saying = Saying::new(); $saying->setContent('嘻嘻哈哈咻咻咻~'); $saying->save(); $id = $saying->getId();
- 数组方式
$data = [ 'content' => '好嗨哟~', ]; $saying = Saying::new($data); $result = $saying->save(); $id = $saying->getId();
- 批量插入
$data = [ ['content' => '好嗨哟~'], ['content' => '你是隔壁的泰山'], ['content' => '打架能增进感情,来,让我们亲热亲热'], ]; $result = Saying::insert($data);
更新数据
-
实体更新,返回 bool 值
$id = 9; $result = Saying::find($id)->update(['content'=>'一想到你我就~~~~']);
-
批量更新,返回受影响行数
$ids = [4,5,6,7]; $result = Saying::whereIn('id',$ids)->update(['content'=>'惊悚有声故事的鼻祖~']);
删除数据
-
实体删除,返回 bool 值
$id = 8; $result = Saying::find($id)->delete();
-
批量删除
$ids = [6,7]; $result = Saying::whereIn('id',$ids)->delete();
聚合查询
count, max,min,avg,sum
$userNum = DB::table('users')->count();
$price = DB::table('orders')->max('price');
$price = DB::table('orders')->where('status', 1)->avg('price');
原生表达式
// select count(*) as `user_count`, `name` from `user`
$users = DB::table('user')
->selectRaw('count(*) as `user_count`, `name`'));
->get();
事务
DB::beginTransaction();
DB::connection()->beginTransaction();
DB::rollBack();
DB::connection()->rollBack();
DB::commit();
DB::connection()->commit();
本作品采用《CC 协议》,转载必须注明作者和本文链接