GORM中的非主键连接表

rpppsulh  于 2023-06-27  发布在  Go
关注(0)|答案(1)|浏览(125)

我正在尝试基于BookData中的非主键字段检索作者的信息。下面你可以看到我的BookData表中有AuthorId,我试图根据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"`
}
o8x7eapl

o8x7eapl1#

您可以使用关键字ForeignKeyReferences。有关更多用例,请参阅official documentation of GORM

import (
    "fmt"
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
    "gorm.io/gorm/logger"
)

type BookData struct {
    Id                string              `gorm:"primary_key;column:book_id"`
    AuthorId          string              `gorm:"column:author_id"`
    Author            AuthorData          `gorm:"ForeignKey:Id;References: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"`
}

var db *gorm.DB

func init() {
    dsn := "user:pass@tcp(127.0.0.1:3306)/temp?charset=utf8mb4&parseTime=True&loc=Local"
    var err error
    db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
        Logger: logger.Default.LogMode(logger.Info),
    })
    if err != nil {
        panic(err)
    }
}

func main() {
    var books []BookData
    err := db.Preload("Author").Preload("PublisherProperty").
        Find(&books).Limit(10).Error
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(books)
    // output:
    // [{1 1 {1 author1} [{1 1 } {1 2 }]} {2 1 {1 author1} []}]
}

相关问题