2017-04-26 67 views
0

我正在更新並從文件插入到DB中的3個表中。我想檢查一切是否正常,如果沒有錯誤發生,以便我可以向用戶顯示成功消息,如果上傳成功了。我怎樣才能做到這一點?Laravel 5.4 - 檢查所有模型插入和更新是否正常

這是我的代碼:

public function upload(Request $request) 
    { 
    if ($request->hasFile('csvFile')) { 
     $file = $request->file('csvFile'); 
     $file->move('uploads', $file->getClientOriginalName()); 
     $this->store($file); 
    } 

    Session::flash('flash_message','File was successfully uploaded.'); 

    return view('home'); 
    } 

    public function store($file) 
    { 
    $path = base_path('public/uploads/' .$file->getClientOriginalName()); 
    $rows = Excel::load($path, function($reader) { })->get()->toArray(); 

    foreach($rows as $row) { 

     $id = $row[4]; 
     $shopeTitle = $row[1]; 
     $price = $row[6]; 
     $mall = $row[5]; 
     $visitors = $row[3]; 

     Shop::updateOrCreate(
     ['id' => $id], 
     ['title' => $shopeTitle] 
    ); 

     Mall::where('id', $id)->update([ 
     'price' => $price, 
     'visitors' => $visitors 
     ]); 

     if ($mall != 41 || $mall!= 42) { 
     DB::table('store_mall')->insert([ 
      'mall' => $price, 
      'store' => $id 
     ]); 
     } 
    } 
    } 

回答

0

我認爲你應該使用交易。 你可以做這樣的事情

try { 
    DB::beginTransaction(); 

    //your insert updates here 

    //if everything ok commit transaction 
    DB::commit(); 
} catch (Exception $ex) { 
    //if errors exist roll back transaction 
    DB::rollBack(); 
} 

更多信息,您可以在Laravel DB Transactions

閱讀
相關問題