php小编柚子在这篇文章中将为大家介绍一个常见的错误信息:“Gorm 事务错误 error = 事务已提交或回滚”。在使用Gorm进行数据库操作时,有时候会遇到这个错误,让人困惑不解。本文将详细解释这个错误的原因以及可能的解决方案,帮助读者解决这个问题,顺利进行数据库操作。
问题内容
我的目标是在下面的代码中进行事务管理。如果其中一项策略出现错误,我会尝试回滚。在测试代码时,我注意到如果回滚或提交命令运行一次,它会给出错误=事务已被提交或回滚第二次。如何解决此错误?
func (d *DistributeService) Distribute(vehicleNumberPlate string, request model.DistributeRequest) (*model.DistributeResponse, error) { var response model.DistributeResponse response.Vehicle = vehicleNumberPlate var routeList []model.RouteResponse tx := d.repo.BeginTransaction() for _, routes := range request.RouteRequest { var routeResponse model.RouteResponse strategy, isStrategyExists := d.strategies[routes.DeliveryPoint] if isStrategyExists { resp, err := strategy.Distribute(routes.Deliveries, vehicleNumberPlate, tx) if err != nil { tx.Rollback() logrus.Errorf("Error while distributing: %v", err) return nil, err } routeResponse.DeliveryPoint = routes.DeliveryPoint routeResponse.Deliveries = *resp routeList = append(routeList, routeResponse) } else { logrus.Errorf("Invalid delivery point: %v", routes.DeliveryPoint) return nil, errors.New("invalid delivery point") } } response.RouteResponse = routeList err := d.checkSackPackagesAreUnloaded() tx.Commit() if err != nil { return nil, err } return &response, nil }
解决方法
您可能在每次调用中使用相同的事务对象。 如果它被关闭一次 - 无论出于何种原因 - 您需要创建一个新的事务对象。
为什么我说您可能使用您询问的相同事务对象?
因为您基本上将指针传递给 d *DistributeService
。
然后使用 tx := d.repo.BeginTransaction()
。我们无法判断该代码的作用,但我很确定您将在此处返回相同的事务对象以供后续运行。
解决方案是每次调用此方法时创建一个新的事务对象,例如使用 tx := db.Begin()
,如 文档 中所述。
以上是Gorm 事务错误 error = 事务已提交或回滚的详细内容。更多信息请关注PHP中文网其他相关文章!

goisidealforbuildingscalablesystemsduetoitssimplicity,效率和建筑物内currencysupport.1)go'scleansyntaxandaxandaxandaxandMinimalisticDesignenhanceProductivityAndRedCoductivityAndRedCuceErr.2)ItSgoroutinesAndInesAndInesAndInesAndineSandChannelsEnablenableNablenableNableNablenableFifficConcurrentscorncurrentprogragrammentworking torkermenticmminging

Initfunctionsingorunautomationbeforemain()andareusefulforsettingupenvorments和InitializingVariables.usethemforsimpletasks,避免使用辅助效果,andbecautiouswithTestingTestingTestingAndLoggingTomaintAnainCodeCodeCodeClarityAndTestesto。

goinitializespackagesintheordertheordertheyimported,thenexecutesInitFunctionswithinApcageIntheirdeFinityOrder,andfilenamesdetermineTheOrderAcractacractacrosmultiplefiles.thisprocessCanbeCanbeinepessCanbeInfleccessByendercrededBydeccredByDependenciesbetenciesbetencemendencenciesbetnependendpackages,whermayleLeadtocomplexinitialitialializizesizization

CustomInterfacesingoarecrucialforwritingFlexible,可维护,andTestableCode.TheyEnableDevelostOverostOcusonBehaviorBeiroveration,增强ModularityAndRobustness.byDefiningMethodSigntulSignatulSigntulSignTypaterSignTyperesthattypesmustemmustemmustemmustemplement,InterfaceSallowForCodeRepodEreusaperia

使用接口进行模拟和测试的原因是:接口允许定义合同而不指定实现方式,使得测试更加隔离和易于维护。1)接口的隐式实现使创建模拟对象变得简单,这些对象在测试中可以替代真实实现。2)使用接口可以轻松地在单元测试中替换服务的真实实现,降低测试复杂性和时间。3)接口提供的灵活性使得可以为不同测试用例更改模拟行为。4)接口有助于从一开始就设计可测试的代码,提高代码的模块化和可维护性。

在Go中,init函数用于包初始化。1)init函数在包初始化时自动调用,适用于初始化全局变量、设置连接和加载配置文件。2)可以有多个init函数,按文件顺序执行。3)使用时需考虑执行顺序、测试难度和性能影响。4)建议减少副作用、使用依赖注入和延迟初始化以优化init函数的使用。

go'SselectStatementTreamLinesConcurrentProgrambyMultiplexingOperations.1)itallowSwaitingOnMultipleChannEloperations,执行thefirstreadyone.2)theDefirstreadyone.2)thedefefcasepreventlocksbysbysbysbysbysbythoplocktrograpraproxrograpraprocrecrecectefnoopeready.3)

contextancandwaitgroupsarecrucialingoformanaginggoroutineseflect.1)context contextsallowsAllowsAllowsAllowsAllowsAllingCancellationAndDeadLinesAcrossapibiboundaries,确保GoroutinesCanbestoppedGrace.2)WaitGroupsSynChronizeGoroutines,确保Allimizegoroutines,确保AllizeNizeGoROutines,确保AllimizeGoroutines


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器