使用嵌套对象更新记录,给出重复键错误
Update a record with nested objects giving duplicate key error
我需要更新用户配置文件,我正在获取整个配置文件,允许用户编辑他想要的内容,然后将整个配置文件再次发送到服务器以保存更新的任何值,但它没有用.
User {
Address {
Country {
// fields
},
// fields
},
Settings {
// fields
},
username: string,
email: string,
}
为了避免复杂化,我想发送整个记录,全部保存,更新任何更新的内容,或者为未更新的字段再次保存旧值。
我试过这个:
// Update User data
func (r *RepositoryUserCrud) Update(uid int, user models.User) (int, error) {
var err error
// 1, did not work, getting Error 1062: Duplicate entry for email
err = r.db.Debug().Model(&models.User{}).Where("id = ?", unit(uid)).Updates(user).Error
// 2, did not work, getting Error 1062: Duplicate entry for email
err = r.db.Save(&user).Error;
// 3, I tried to skip the duplicate key error by using {onConflict: DoNothing}
err = r.db.Debug().Clauses(r.db.Model(&models.User{})
.Where("id = ?", uint(uid)))
.OnConflict{DoNothing: true}
.Updates(user)
}
关于如何使这项工作有任何建议吗?
如果更改发生在深层嵌套的对象中,如何将更改应用到它们的表中?还是我应该手动执行此操作?
事实证明电子邮件字段是主键,我没有将 ID 作为更新记录的一部分传递,所以它基本上是在尝试使用相同的电子邮件创建新记录。
因此此代码有效,但请确保 ID
提供记录本身。
err = r.db.Debug().Model(&models.User{}).Where("id = ?", unit(uid)).Updates(user).Error
我还需要手动更新其他表中的链接行。
我需要更新用户配置文件,我正在获取整个配置文件,允许用户编辑他想要的内容,然后将整个配置文件再次发送到服务器以保存更新的任何值,但它没有用.
User {
Address {
Country {
// fields
},
// fields
},
Settings {
// fields
},
username: string,
email: string,
}
为了避免复杂化,我想发送整个记录,全部保存,更新任何更新的内容,或者为未更新的字段再次保存旧值。
我试过这个:
// Update User data
func (r *RepositoryUserCrud) Update(uid int, user models.User) (int, error) {
var err error
// 1, did not work, getting Error 1062: Duplicate entry for email
err = r.db.Debug().Model(&models.User{}).Where("id = ?", unit(uid)).Updates(user).Error
// 2, did not work, getting Error 1062: Duplicate entry for email
err = r.db.Save(&user).Error;
// 3, I tried to skip the duplicate key error by using {onConflict: DoNothing}
err = r.db.Debug().Clauses(r.db.Model(&models.User{})
.Where("id = ?", uint(uid)))
.OnConflict{DoNothing: true}
.Updates(user)
}
关于如何使这项工作有任何建议吗?
如果更改发生在深层嵌套的对象中,如何将更改应用到它们的表中?还是我应该手动执行此操作?
事实证明电子邮件字段是主键,我没有将 ID 作为更新记录的一部分传递,所以它基本上是在尝试使用相同的电子邮件创建新记录。
因此此代码有效,但请确保 ID
提供记录本身。
err = r.db.Debug().Model(&models.User{}).Where("id = ?", unit(uid)).Updates(user).Error
我还需要手动更新其他表中的链接行。