我使用事务后如何重定向并抛出新的\ Exception('错误');从下面的代码中我发现错误它停在其他地方{throw new \ Exception(' Error');}和我的if($ errors)无法正常工作
是他们在抛出new \ Exception()之后重定向的吗?
$errors = false;
DB::transaction(function () use ($count,$request,$a,$errors) {
for ($i=0; $i < $count; $i++) {
$warehouse_products_sell = New Warehouse_products_sell;
$id_w = $request->input('idw');
$id_c = $request->get('id_c')[$i];
$id_p = $request->get('id_p')[$i];
$qty = $request->input('quantity_box')[$i];
$price = $request->input('price')[$i];
$available = $this->check_stock($id_w, $id_p, $qty);
if($available > 0){
$warehouse_products_sell->save();
}else{
echo "error";
$errors = true;
throw new \Exception('Error');
}
}
});
if ($errors) {
return redirect('URL');
}else{
return 'x';
}
答案 0 :(得分:1)
不要在没有数据库事务的情况下自行检查数据库事务:
// Step 1. Check all products
$products = [];
for ($i=0; $i < $count; $i++) {
$warehouse_products_sell = New Warehouse_products_sell;
$id_w = $request->input('idw');
$id_c = $request->get('id_c')[$i];
$id_p = $request->get('id_p')[$i];
$qty = $request->input('quantity_box')[$i];
$price = $request->input('price')[$i];
$available = $this->check_stock($id_w, $id_p, $qty);
if ($available <= 0){
throw new \Exception(sprintf('Not enough stock for %s/%s (stock=%d, requested=%d)', $id_w, $id_p, $available, $qty));
}
$products[] = $warehouse_products_sell
}
// Step 2. All checks have passed, save data to database
DB::transaction(function () use ($products) {
foreach ($products as $product) {
$product->save();
}
});