pg icon indicating copy to clipboard operation
pg copied to clipboard

Queries with has-many relationships are not idempotent

Open betaprior opened this issue 4 years ago • 0 comments

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 // ???!!

betaprior avatar May 07 '20 08:05 betaprior