php - 如果发生错误,如何避免数据插入?(有几个插入的方法)在 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([])
}
如您所见,我有很多插入。
如果发生错误(或者如果用户在某个时候失去了连接),它将破坏我的数据库的完整性,因为我的方法将添加第一个元素而不是其他元素。
我这样想是对的吗?如何避免这种情况?
解决方案
您可以使用 laravel 数据库事务。
如果任何数据库查询失败,它将自动回滚先前的查询。DB::transaction(function () {
//set of queries
//example
DB::table('users')->update(['votes' => 1]);
DB::table('posts')->delete();
});
推荐阅读
- java - 为什么 .equals() 方法没有被 Java 中的基元数组覆盖?
- javascript - 每次使用 D3 V3 或 JavaScript 单击按钮时,使 svg 元素的颜色变暗
- python - 使用 Apache Beam 连接到本地 App Engine 数据存储区
- visual-studio-2017 - 未找到指定的 Microsoft.NETCore.App',版本 '2.0.7'
- javascript - Javascript:如果滚动到特定目标淡出,如果再次向上滚动,则淡入
- spring - 为单个 Spring Boot 实例配置多个模板解析器
- java - 自动发送电子邮件
- angular6 - angular 6 通用问题“未找到模块:错误:无法解析“/var/www/html/angular6/testing”中的“./dist/server/main”
- javascript - 通过 ajax 请求观察 div 突变
- javascript - Jquery .load 用于烧瓶\python 上的更新片段