pg
pg copied to clipboard
Queries with has-many relationships are not idempotent
When issuing several queries on the same model, the list representing the "many" side of the relationship gets appended with identical entities. This is undocumented and very surprising since one would assume idempotency of queries.
Adapting an existing example:
type Profile struct {
Id int
Lang string
UserId int
}
type User struct {
Id int
Name string
Profiles []*Profile
}
u0 := &User{ Name: "Vasya" }
err = db.Insert(u0)
p0 := &Profile{ UserId: u0.Id, Lang: "en" }
db.Insert(p0)
vasya := &User{}
err = db.Model(vasya).Where("id = ?", u0.Id).Relation("Profiles").Select()
// len(vasya.Profiles) == 1 // OK
err = db.Model(vasya).Where("id = ?", u0.Id).Relation("Profiles").Select()
// len(vasya.Profiles) == 2 // ???!!