2017-10-01 49 views
0

我如何重新定向后,我使用交易和抛出新\异常('错误');从我的代码下面,当我有一个错误它停止在其他{抛出新\异常('错误');}和我如果($错误)不起作用我如何重新定向后,我使用交易,并抛出新的异常('错误')

是他们无论如何重定向后抛出新\例外)?

$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

抓住它,然后.. RTM http://php.net/manual/en/internals2。 opcodes.catch.php –

+0

@LawrenceCherone我试图捕捉,但如果我有3个正确的数据和1个错误的数据它会保存3个数据我想拒绝所有不知道我做正确的事虐待再试一次。 – user8663822

+1

然后在catch部分使用break。 –

回答

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(); 
    } 
}); 
+0

谢谢你这里是我第一次使用transacrions – user8663822