2017-04-26 68 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

阅读
相关问题