首页 > 解决方案 > 使用 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

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

标签: postgresqlgogo-gorm

解决方案


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

推荐阅读