使用gorm更新postgres表

时间:2019-02-16 08:12:38

标签: postgresql go go-gorm

我在尝试更新表中的行时遇到麻烦。 我尝试了以下方法:

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

任何帮助或建议将不胜感激!谢谢。

1 个答案:

答案 0 :(得分:1)

解决方案是在表中查找记录,然后在使用.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
}