我想直接在5个表中存储数据。我成功地将数据存储/保存在4个表中,但是在最后一个表中出现错误。如何回滚前4个表中的记录?
这是我的控制器
$booking = new Book();
$booking->date = Carbon::now();
$booking->unique_number = mt_rand(1, 999);
$booking->save();
$bookingDetail = new BookDetail();
$bookingDetail->book()->associate($booking);
$bookingDetail->qty = $request->qty;
$bookingDetail->event_id = $id;
$bookingDetail->price = $event->price;
$bookingDetail->subtotal = $bookingDetail->qty * $bookingDetail->price;
$bookingDetail->save();
$booking->total = $bookingDetail->subtotal + $booking->unique_number;
$booking->save();
$bookingConfirmation = new BookConfirmation();
$bookingConfirmation->book()->associate($booking);
$bookingConfirmation->save();
$bookingCompletion = new BookCompletion();
$bookingCompletion->book()->associate($booking);
$bookingCompletion->save();
$participants = explode(', ', $request->participant_name);
if(count($participants) === $bookingDetail->qty){
foreach ($participants as $participant) {
$bookingParticipant = new BookParticipant();
$bookingParticipant->participant_name = $participant;
$bookingParticipant->save();
}
}else{
echo '<script language="javascript">alert("Jumlah orang tidak sesuai")</script>';
}
答案 0 :(得分:1)
您可以通过rollBack方法回滚事务:
DB::rollBack();
如果您想手动开始事务并完全控制回滚和提交,可以在数据库外观上使用beginTransaction方法:
DB::beginTransaction();
您可以使用try catch块,如果有任何想法出错,那么在catch块中您可以回滚您的交易
DB::beginTransaction();
try{
here you can add your code to exicute and commit db transaction
} catch (Exception $e) {
DB::rollback();
}
价: https://laravel.com/docs/5.5/database#database-transactions
这里也已经回答了堆栈问题 Laravel: Using try...catch with DB::transaction()