GO GORM .Related()构造不使用非默认主键名。

时间:2016-04-05 12:45:23

标签: go go-gorm

使用“默认”主键命名约定时:

POSTGRES表

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)
)

这个.Related()构造在每个示例中都可以正常工作:

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)

但是当使用非默认主键名称时,该示例不起作用。无论有多少电子邮件,只有一封电子邮件被添加到电子邮件中。

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)

我不得不求助于使用这个结构:

person := models.Person{}
conn.DB.First(&person)
conn.DB.Where("person_id = ?", person.PersonId).Find(&person.Emails)

在这种情况下是否可以使.Related()工作?

1 个答案:

答案 0 :(得分:0)

发现了这个问题。以下是更正后的结构:

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")