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();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章