How to update with a has many relationship

Viewed 456

I use the gorm with the has many。 This is my model

type Pro struct {
    Model
    TaxRate              []TaxRate  `json:"taxRate" gorm:"constraint:OnUpdate:CASCADE;"`
}
type TaxRate struct {
    ID        uint
    Tax       float64
    ProjectID uint
}

but when I update the project, I found that the TaxRate just insert the record not update. This is my update operation

result:=pRepo.db.Session(&gorm.Session{FullSaveAssociations: true}).Updates(p)
1 Answers

According to the gorm documentation on has-many relationships (https://gorm.io/docs/has_many.html) the automatic relation needs to be structnameID, so in your case ProID (the owner struct is called Pro and not Project). Either rename the struct or the reference or add gorm:"foreignKey:ProjectID" as tag:

type Pro struct {
    Model
    TaxRate []TaxRate `json:"taxRate" gorm:"foreignKey:ProjectID;constraint:OnUpdate:CASCADE;"`
}
Related