首页 > 解决方案 > 如果发生错误,如何避免数据插入?(有几个插入的方法)在 Laravel

问题描述

我正在构建一个 Web 应用程序,并且我知道可能存在问题。

我有一个控制器,其中有一个store方法。此方法在数据库中创建多个插入。

public function store(LocationPostRequest $request)
{
  $location = Location::create([...]);
  $order = new Order([...]);
  $location->order()->save($order);
  $contact = Contact::findOrFail(id);
  $order->contacts()->save($contacts);
  Transaction::create([])
}

如您所见,我有很多插入。

如果发生错误(或者如果用户在某个时候失去了连接),它将破坏我的数据库的完整性,因为我的方法将添加第一个元素而不是其他元素。

我这样想是对的吗?如何避免这种情况?

标签: phplaraveldatabase-integrity

解决方案


您可以使用 laravel 数据库事务。

如果任何数据库查询失败,它将自动回滚先前的查询。
DB::transaction(function () {
    //set of queries
   //example 
   DB::table('users')->update(['votes' => 1]);
   DB::table('posts')->delete();
});

推荐阅读