postgresql - 使用 gorm 更新 postgres 表
问题描述
我在尝试更新表中的行时遇到问题。我尝试了以下方法:
return ss.db.Where("name = ?", sub.Name).Save(&sub).Error
和
return ss.db.Save(sub).Error
我也尝试过这个的变体
s := ss.db.Where("Name = ?", sub.Name)
return ss.db.Model(&s).Updates(Subscription{Name: sub.Name, DevicesAllowed: sub.DevicesAllowed, Price: sub.Price, Active: sub.Active}).Error
我还尝试了其他几种无效的方法,例如,这种尝试导致所有行都被更改:
return ss.db.Model(&sub).Updates(Subscription{Name: sub.Name, DevicesAllowed: sub.DevicesAllowed, Price: sub.Price, Active: sub.Active}).Error
我在这里有其余代码供参考:https ://gist.github.com/yshuman1/8a26a90507bc13de7290d3adc0facdd1
任何帮助或建议将不胜感激!谢谢你。
解决方案
解决方案是在表中找到记录,然后在使用 .Save() 之前用新值替换旧值,如下所示:
func (ss *SubscriptionService) Update(sub *Subscription) error {
var subscription Subscription
db := ss.db.Where(&Subscription{Name: sub.Name})
err := first(db, &subscription)
if err != nil {
log.Error("error looking up subscription")
return err
}
subscription.Price = sub.Price
subscription.Active = sub.Active
subscription.DevicesAllowed = sub.DevicesAllowed
return ss.db.Save(&subscription).Error
}
推荐阅读
- angular - 如何在其他库 nx (nrwl) 中共享库 - singlerepo
- javascript - firebase 实时数据库:根据几个条件更新我表中的特定项目
- java - JSONObject(response.body().toString()) 是空对象
- c# - 如何组织具有多个 parentID 级别的 ac# 列表
- ios - 未能执行单击导航栏自定义按钮
- r - 按列对数据框进行排序,其名称作为向量传递
- c# - C# List 按值而不是按引用
- spring-data-neo4j - 添加关系实体属性
- javascript - 如何在 addEventListener() 中定义 onClick() 函数
- c++ - 无法逐行读取 .csv 文件