mysql - gorm 是否共享先前交易中的 ID 创建
问题描述
我有一个查询,需要上一个插入的 ID。gorm 是否在事务模式下泄露了 ID:
例子:
err := db.Transaction(func(tx *gorm.DB) error {
if err := tx.Model(&model.user).Create(&user).Error; err != nil {
tx.Rollback()
}
// if user inserted get the user ID from previous user insert of DB
for _, v := profiles {
v.UserID = user.ID // Can I get this ID from previous Create operation?
}
if err := tx.Model(&model.profile).Create(&profiles).Error; err != nil {
tx.Rollback()
}
})
解决方案
是的,您可以使用 Find 功能来获取您创建的数据。
if err := tx.Model(&model.profile).Create(&profiles).Find(&profiles).Error; err != nil {
tx.Rollback()
}
推荐阅读
- chisel - chisel 和 When 块中的声明和变量范围
- c# - 远离目的地的代理不动| 导航网格
- python - 如何在python中正确比较两个不同的大excel文件中的行和列?
- button - 如何快速更改按钮的颜色
- c# - NHibernate QueryOver Where Or 属性和嵌套集合
- html - 如何从亚马逊拉取产品的图片和标题?
- ios - UI 元素在 UIScrollView swift 中不起作用
- mysql - 如何在 MySQL Workbench 中同时导入多个 DB?
- scala - Scala中这个表达式中'_.nextInt'的值是什么
- python - 使用循环创建同一图像的多个实例,我可以独立移动图像的每个实例吗?