Gorm自动识别添加或更新记录
Reverse Lv4

介绍

写业务时需要用到 gorm 然后有个需求是根据某个字段(主键)来判断记录是否已存在,如果不存在,则创建这条记录,如果存在则更新.

上代码

:::tip 注意!!!
这里user_id字段必须是唯一索引,必须带有uniqueIndex标签,因为 gorm 在判断记录是否存在时,就是根据这个字段来判断的,如果这个字段不是唯一索引,则不会触发OnConflict
:::

  • 表结构
1
2
3
4
5
6
7
8
9
10
11
12
13
14
type RealAuth struct {
gorm.Model
UserID uint `gorm:"column:user_id;type:integer;comment:用户ID;not null;uniqueIndex"` // 用户ID,唯一索引
RealName string `gorm:"column:real_name;type:varchar(255);comment:实名认证姓名"`
IDCard string `gorm:"column:id_card;type:varchar(255);comment:身份证号"`
Ethnicity string `gorm:"column:ethnicity;type:varchar(255);comment:民族"`
BirthDate string `gorm:"column:birth_date;type:varchar(255);comment:出生日期"`
Sex string `gorm:"column:sex;type:varchar(255);comment:性别"`
Address string `gorm:"column:address;type:varchar(255);comment:住址"`
IssueAuthority string `gorm:"column:issue_authority;type:varchar(255);comment:签发机关"`
ValidPeriod string `gorm:"column:valid_period;type:varchar(255);comment:有效期"`
IDCardFrontUrl string `gorm:"column:id_card_front_url;type:varchar(255);comment:身份证正面URL"`
IDCardBackUrl string `gorm:"column:id_card_back_url;type:varchar(255);comment:身份证反面URL"`
}
  • 代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

/*
更新或添加身份证正面照信息
1. ctx: 上下文
2. userID: 用户ID
3. resp: 身份证正面照信息
4. url: 身份证正面照在线URL
*/
func (r *userRepository) UserRealAuth(ctx context.Context, userID uint, resp v1.OcrFrontContent, url string) error {
// 如果记录不存在则创建,存在则更新
realAuth := model.RealAuth{
UserID: userID,
RealName: resp.Name,
IDCard: resp.IDNumber,
Ethnicity: resp.Ethnicity,
BirthDate: resp.BirthDate,
Sex: resp.Sex,
Address: resp.Address,
IDCardFrontUrl: url,
}
return r.DB(ctx).Model(&model.RealAuth{}).Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "user_id"}},
DoUpdates: clause.AssignmentColumns([]string{
"id_card_front_url",
"real_name",
"id_card",
"ethnicity",
"birth_date",
"sex",
"address",
}),
}).Create(&realAuth).Error
}

介绍

代码中,根据user_id来判断记录是否存在,如果存在则更新,不存在则创建,值得一提的时,user_id是唯一索引,也必须是唯一索引,所以不会出现重复创建的情况

当发现user_id记录已存在时,则根据clause.AssignmentColumns里面提供的字段来更新记录,这里更新了

  • id_card_front_url
  • real_name
  • id_card
  • ethnicity
  • birth_date
  • sex
  • address