When using the "default" primary key naming convention:
POSTGRES tables
CREATE TABLE person
(
id SERIAL,
name varchar(255) NOT NULL,
CONSTRAINT person_pk PRIMARY KEY (id)
)
CREATE TABLE email
(
id SERIAL,
person_id int NOT NULL REFERENCES person(id),
CONSTRAINT email_pk PRIMARY KEY (id)
)
This .Related() construct works fine per the examples:
type Person struct {
ID int
Name string
Emails []Email
}
type Email struct {
ID int
PersonID int
}
person := models.Person{}
conn.DB.First(&person).Related(&person.Emails)
But when using non-default primary keys names, the example does not work. Only one email is added to Emails regardless of how many there are.
CREATE TABLE person
(
person_id SERIAL,
name varchar(255) NOT NULL,
CONSTRAINT person_pk PRIMARY KEY (person_id)
)
CREATE TABLE email
(
email_id SERIAL,
person_id int NOT NULL REFERENCES person(person_id),
CONSTRAINT email_pk PRIMARY KEY (email_id)
)
type Person struct {
PersonId int `gorm:"primary_key"`
Name string
Emails []Email `gorm:"ForeignKey:PersonId"`
}
type Email struct {
EmailId int `gorm:"primary_key"`
PersonId int
}
person := models.Person{}
conn.DB.First(&person).Related(&person.Emails)
I've had to resort to using this construct:
person := models.Person{}
conn.DB.First(&person)
conn.DB.Where("person_id = ?", person.PersonId).Find(&person.Emails)
Is it possible to make .Related() work in this case?
Found the issue. Here are the corrected structs:
type Person struct {
PersonId int `gorm:"primary_key"`
Name string
Emails []Email `gorm:"ForeignKey:PersonRefer"`
}
type Email struct {
EmailId int `gorm:"primary_key"`
Person Person
PersonRefer int `gorm:"column:person_id"`
}
conn.DB.First(&person).Related(&person.Emails, "PersonRefer")