保存时是否有任何方法可以在Laravel中执行试运行?
可以说我有两个模型,Booking
和BookingDetails
。我不希望其中一个保存而没有另一个。
此刻,我正在像这样填充储蓄:
// Create new booking
try
{
$booking = with(new Booking)->fill(request()->all())->save();
$bookingDetails = with(new BookingDetails)->fill(request()->all())->save();
}
catch (\Exception $e)
{
// Die quietly
}
理想情况下,我希望能够首先查看预订保存,因为如果预订保存不起作用,则我不想保存详细信息。然后,如果无法保存详细信息,那么我不想首先保存预订,我只想抛出一个错误,如果任何一个失败,则保存什么都不会。
有什么方法可以让我进行试运行并测试所有保存工作,如果可以,并且都可以保存,那么可以保存吗?而不是像这样
// Create new booking
try
{
$booking = with(new Booking)->fill(request()->all())->save();
try
{
$bookingDetails = with(new BookingDetails)->fill(request()->all())->save();
}
catch (\Exception $ex)
{
// Find the booking here and delete, because the details cant be saved
}
}
catch(\Exception $e)
{
// Die quietly
}
答案 0 :(得分:3)
DB Transaction是您要寻找的。
DB事务仅在两个都很好时保存booking
和bookingDetails
。如果它们中的任何一个失败,则不会保存任何内容。
DB::transaction(function () {
$booking = with(new Booking)->fill(request()->all())->save();
$bookingDetails = with(new BookingDetails)->fill(request()->all())->save();
}, 5);