'gorm golang with multiple has one
I'm having trouble finding the right annotations for multiple has one which reference the same table. something like this:
type Pet struct {
gorm.Model
Name string
}
type PetOwner struct {
gorm.Model
LargestPet *Pet
SmallestPet *Pet
AllOthers []*Pet
}
Does anybody know what annotations and what explicit id fields would allow this to work?
Many thanks!
Solution 1:[1]
I got this working as follows:
type PetOwner struct {
gorm.Model
LargestPetID uint
LargetPet *Pet `gorm:"foreignKey:LargestPetID`
SmallestPetID uint
SmallestPet *Pet `gorm:"foreignKey:SmallestPetID`
AllOthers []*Pet
}
and then loading the data as follows:
var petOwner PetOwner
db.Joins("AllOthers").Joins("SmallestPet").Joins("LargestPet").Find(&petOwner)
If you want to access from the pet for which owner it is the largest pet, you can modify the pet definition as follows:
type Pet struct {
gorm.Model
...
LargestPetOf *PetOwner `gorm:"foreignKey:LargestPetID"
}
and then load this with a .Join("LargestPetOf")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ehrt1974 |
