首页 > 解决方案 > 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()
    }
})

标签: mysqlgogo-gorm

解决方案


是的,您可以使用 Find 功能来获取您创建的数据。

if err := tx.Model(&model.profile).Create(&profiles).Find(&profiles).Error; err != nil {
     tx.Rollback()
}

推荐阅读