gpt4 book ai didi

php - 在保存到数据库之前如何检查循环中的所有数据

转载 作者:行者123 更新时间:2023-11-28 23:08:42 25 4
gpt4 key购买 nike

现在在我的 Controller 中它看起来像这样

assume that $available = [ 1,2,3,4 ]

for ($i=0; $i < 3; $i++) {
if($available < 3){
echo 'success';
$database->save();
}else{
echo 'error';
}
}

这会输出类似success success success error

它会将 3 个成功保存到数据库中,我如何检查我是否有 1 个错误它不会保存任何数据?

现在我在用

   $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->add_by = $request->input('add_by');

$warehouse_products_sell->id_w = $id_w = $request->input('idw');
$warehouse_products_sell->id_c = $request->get('id_c')[$i];
$warehouse_products_sell->id_p = $id_p = $request->get('id_p')[$i];
$warehouse_products_sell->quantity_box = $qty = $request->input('quantity_box')[$i];
$warehouse_products_sell->price = $request->input('price')[$i];
$warehouse_products_sell->serial_num = $a;
$available = $this->check_stock($id_w, $id_p, $qty);
$warehouse_products_sell->save();
}else{

echo "error";
$errors = true;

throw new Exception('Error');
}
}
});
if ($errors) {
return redirect('URL');
}else{
return 'x';
}

最佳答案

您可以使用交易。看看here .

你的代码会变成这样

DB::transaction(function () use ($database, $available) {
for ($i=0; $i < 3; $i++) {
if($available < 3){
echo 'success';
$database->save();
}else{
echo 'error';
throw new \Exception('Error');
}
}
});

如果抛出异常,会自动回滚。


如果出现任何问题添加重定向

$errors = false;

DB::transaction(function () use ($database, $available, $errors) {
for ($i=0; $i < 3; $i++) {
if($available < 3){
echo 'success';
$database->save();
}else{
echo 'error';
$errors = true;
throw new \Exception('Error');
}
}
});

if ($errors) {
return redirect('URL');
}

关于php - 在保存到数据库之前如何检查循环中的所有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46509121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com