Maximus S
Maximus S

Reputation: 11125

Trouble defining inter-table relationship

Goal

I am trying to setup a simple has_many association with Gorm: a person has many pets.

Problem

I see the following error when I try to save the Person model.

unsupported type []model.Pet, a slice of struct

Details

Assume I want to save an Person that has many Pets.

type Person struct {
    UUID `gorm:"PRIMARY_KEY" json:"uuid"`
    Pet  []Pet `gorm:"foreignkey:PersonUUID:association_foreignkey:UUID"`
}

type Pet struct {
    UUID `gorm:"PRIMARY_KEY" json:"uuid"`
  PersonUUID string
}

Then I try to create these two models.

personUUID := "dcf4b3c6-d94c-4b2c-9d66-1cbaedd2cc44"
pets := []Pet{
  Pet{
    UUID: "..",
    PersonUUID: personUUID,
  }
}
person := Person{
  UUID: personUUID,
  Pet: Pet,
}

db.Where("uuid = ?", person.UUID).Update(&person)

Then I get the following error.

sql: converting argument $1 type: unsupported type []model.Pet, a slice of struct

Any idea why this might be happening?

Upvotes: 1

Views: 263

Answers (1)

Maximus S
Maximus S

Reputation: 11125

I found out it only happens if you use Update instead of Save. This is odd, because both should work the same way except that Update will try to save the different fields while Save will replace the current values with the new values.

Upvotes: 0

Related Questions