【问题标题】:How to rollback new records if another record fails to save/store如果另一条记录无法保存/存储,如何回滚新记录
【发布时间】:2018-03-02 23:41:33
【问题描述】:

我想直接将数据存储在 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>';
}

【问题讨论】:

标签: php mysql database laravel-5


【解决方案1】:

您可以通过rollBack方法回滚事务:

DB::rollBack();

如果您想手动开始事务并完全控制回滚和提交,您可以使用 DB 外观上的 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()

【讨论】:

  • 我看过文档..但我不明白如何在我的代码中实现它..你能给我一个示例吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-08
  • 2014-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多