Gorm2 使用UUID时,多对多会创建重复记录的处理方案

type BaseEntity struct {
	ID         string     `gorm:"type:varchar(36);primary_key;comment:主键"`
	CreateBy   string     `gorm:"type:varchar(64);default:system;comment:创建人"`
	UpdateBy   string     `gorm:"type:varchar(64);default:system;comment:更新人"`
	CreateTime *time.Time `gorm:"comment:创建时间;autoCreateTime"`
	UpdateTime time.Time  `gorm:"comment:更新时间;autoUpdateTime"`
}

func (b *BaseEntity) BeforeCreate(tx *gorm.DB) (err error) {
    uuid := uuid.NewV4().String()
	b.ID = strings.ReplaceAll(uuid, "-", "")
	return
}

参考网络上的方案,自己就加了一个去掉中间 - 的代码

在多对多时,发现会不断的创建记录

后来发现将ID改成int后不会重复创建了

估计是创建的时候不断创建新的uuid了,于是加上了判断,问题解决...

到处百度都没找到答案,特地留下该解决方案

type BaseEntity struct {
	ID         string     `gorm:"type:varchar(36);primary_key;comment:主键"`
	CreateBy   string     `gorm:"type:varchar(64);default:system;comment:创建人"`
	UpdateBy   string     `gorm:"type:varchar(64);default:system;comment:更新人"`
	CreateTime *time.Time `gorm:"comment:创建时间;autoCreateTime"`
	UpdateTime time.Time  `gorm:"comment:更新时间;autoUpdateTime"`
}

func (b *BaseEntity) BeforeCreate(tx *gorm.DB) (err error) {
	if b.ID == "" {
		uuid := uuid.NewV4().String()
		b.ID = strings.ReplaceAll(uuid, "-", "")
	}
	return
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值