duanqiang3925 2018-08-21 11:26
浏览 75

更新字段将创建新的外键项,而不是对其进行更新

I've got a one-to-one relationship, Location, working with postgresql:

type App struct {
    gorm.Model

    PersoID      string `gorm:"primary_key;unique" json:"perso_id"`

    Location   OllyLocation `gorm:"foreignkey:location_id"`
    LocationID *uint        `json:"-" gorm:"type:integer REFERENCES locations(id)"`

    Users          []User       `json:"users,omitempty" gorm:"many2many:app_users;"`
}

type Location struct {
    ID        uint      `json:"-" gorm:"primary_key;unique"`
    CreatedAt time.Time `json:"-"`
    UpdatedAt time.Time

    Lat         float64 `json:"lat"`
    Long        float64 `json:"long"`
    Address     string  `json:"address"`
    Country     string  `json:"country"`
}

But as you can see, the App structure has its own primaryKey id as string (and the GORM one). Thus this block from doing a simple db.Save() from gorm.

So I've tried to do:

func (previousModel *App) UpdateAndReturnedUpdated(db *gorm.DB, appUpdated *App) error {
    if err := db.Model(previousModel).Update(appUpdated).Error; err != nil {
        return err
    }

    return db.Preload("Location").First(previousModel, App{PersoID: appUpdated.PersoID}).Error
}

With this, the App is correctly updated - fantastic! - but not the Location.

The location is re created in the db with the new values and the foreignKey LocationID is updated on the App.

This is super annoying because if I want to do an update of the address only without specifying other fields, they are just re created with the original type value (lat / long will be 0)

Any ideas about how to update the foreignKey? Thanks!

  • 写回答

2条回答 默认 最新

  • doumaikuang4202 2018-08-21 12:12
    关注

    You can use this to not modify the associated entities

    db.Set("gorm:save_associations", false).Save(previousModel)

    or to save only one field of the struct

    db.Model(previousModel).UpdateColumn("PersoID", appUpdated.PersoID)

    if you want to update an associated entity and not the relation you will need to update the entity itself

    db.Model(Location{ID:*previousModel.LocationID}).Update(appUpdated.Location)

    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line