1.laravel中使用事務
DB::beginTransaction();//開啟事務 try { $row = LikesDetails::create(['article_id' => $article_id, 'review_id' => $review_id, 'member_id' => $member_id, 'update_time' => $time,'is_liked' => $is_liked, 'create_time' => $time]); $likes = Article::where(['id' => $article_id])->value('praise'); $likes += 1; Article::where(['id' => $article_id])->update(['praise' => $likes, 'update_time' => $time]); DB::commit();//提交事務 $message = '新增成功'; } catch (Exception $e) { DB::rollBack();//事務回滾 $message = '新增失敗'; }
如果在事務的閉包中出現了異常,事務將會自動回滾。如果閉包執行成功,事務將會自動提交。在使用 transaction
方法時不需要手動回滾或提交
DB::transaction(function () { DB::update('update users set votes = 1'); DB::delete('delete from posts'); });