Skip to content

create、update、delete

Create:Clauses

go
func (r *UserRoleRepo) Create(ctx context.Context, userID, roleID uint) error {
	model := &iamdomian.UserRoleModel{
		UserID: userID,
		RoleID: roleID,
	}

	return r.db.WithContext(ctx).
		Clauses(clause.OnConflict{DoNothing: true}).
		Create(model).Error
}

基础 Update

go
err := db.WithContext(ctx).
    Model(&UserModel{}).
    Where("id = ?", userID).  
    Updates(map[string]any{ // 注意是 Update s,有个 s
        "name":  "张三",
        "email": "xxx@qq.com",
    }).Error
go
err := db.WithContext(ctx).
    Model(&UserModel{}).
    Where("id = ?", userID).
    Updates(&UserModel{
        Name:  "张三",  // 结构体字段,自动转数据库字段
        Email: "xxx@qq.com",
    }).Error

默认不会更新 零值。

如果要更新 零值 必须使用 select

go
db.Model(&User{}).Where("id=?",1).
    Select("name", "age").
    Updates(User{Name: "", Age: 0})

Delete:软删与硬删

GORM 默认就是软删

go
func DeleteApp(ctx context.Context, id uint) error {
	return db.GetInstance().WithContext(ctx).Where("id = ?", id).Delete(&model.App{}).Error
}

硬删:

go
// 软删与硬删的区别仅仅只是 Unscoped()
func DeleteApp(ctx context.Context, id uint) error {
	return db.GetInstance().WithContext(ctx).Unscoped().Where("id = ?", id).Delete(&model.App{}).Error
}