在GORM中使用非主键联接表

时间:2019-12-20 15:40:43

标签: go go-gorm

我正在尝试基于BookData中不是主键的字段来检索作者的信息。在下面的表格中,您可以看到我的AuthorId表中有BookData,尽管它不是主键,但我仍试图根据该AuthorId来获取作者。看来GORM不支持这种类型的联接,有办法吗?

您还可以在下面看到我能够正确获取PublisherProperty信息,因为它的外键是BookData的主键。我只是想知道如果不是主键怎么办。预先感谢!

type BookData struct {
    Id                string              `gorm:"primary_key;column:book_id"`
    AuthorId          string              `gorm:"column:author_id"`
    Author            AuthorData          `gorm:"foreignkey:AuthorId"`
    PublisherProperty []PublisherProperty `gorm:"foreignkey:Id"`
}

type AuthorData struct {
    Id    string `gorm:"primary_key;column:author_id"`
    Name  string `gorm:"column:author_name"`
}


type PublisherProperty struct {
    Id           string `gorm:"primary_key;column:book_id"`
    PublisherId  string `gorm:"primary_key;column:publisher_id"`
    PublisherTxt string `gorm:"column:publisher_txt"`
}

0 个答案:

没有答案