我有以下代码:
$new_models = DB::transaction(function () use ($supplier, $address, $addressDetail) {
$new_supplier = $this->setNewSupplier($supplier);
$new_address = $this->setNewAddress($address);
$new_addressDetail = $this->setNewAddressDetail($addressDetail,$new_address->id);
$this->syncSupplierAddress($new_supplier->id,$new_address->id);
$this->updateControlAp($new_supplier->supplier_id);
return [$new_supplier, $new_address, $new_addressDetail];
});
set方法基本上是在最后用save()创建模型对象;
现在,如果第二个... nth失败,这完全正常,但如果第一个失败则不行。
如果$this->setNewSupplier($supplier);
失败比我得到
"PDOException in Connection.php line 541:
There is no active transaction"
我在这里做错了吗?此外,如果我从供应商Connection.php中的catch中评论$this->rollBack();
,它实际上给了我SQL错误。这里重要的一点是,只有在第一次save()失败时才能使用
PS。我使用PostgreSQL而不是MySQL,但我不认为它是相关的
答案 0 :(得分:0)
在Laravel中有不同的交易方式,另一种可能是:
...
$new_models = [];
try {
DB::beginTransaction();
$new_supplier = $this->setNewSupplier($supplier);
$new_address = $this->setNewAddress($address);
$new_addressDetail = $this->setNewAddressDetail($addressDetail,$new_address->id);
$this->syncSupplierAddress($new_supplier->id,$new_address->id);
$this->updateControlAp($new_supplier->supplier_id);
$new_models = [$new_supplier, $new_address, $new_addressDetail];
DB::commit();
} catch(\Exception $e) {
DB::rollback();
// Handle Error
}
...