gpt4 book ai didi

go - 我应该如何用一个外键引用两个表?

转载 作者:行者123 更新时间:2023-12-03 10:06:33 28 4
gpt4 key购买 nike

我有一个公司模型,我有一个客户模型。两者都可以是关系。

type Customer struct {
gorm.Model
Title string
}

type Company struct {
gorm.Model
Title string
}

type Relation struct {
gorm.Model
CustomerOrCompanyID uint
}
所以两者是一种关系。我怎样才能让我的关系指向公司或客户?

最佳答案

有一种方法可以在 Gorm 中使用多态的 Has One 关系自然地做到这一点。这将使您能够轻松运行@TheSphinX 提供的一些查询。
但是,您需要在关系表中添加一个类型鉴别器列才能使其工作:

type Customer struct {
gorm.Model
Title string
Rel Relation `gorm:"polymorphic:Owner"`
}

type Company struct {
gorm.Model
Title string
Rel Relation `gorm:"polymorphic:Owner"`
}

type Relation struct {
gorm.Model
Foo string
OwnerID uint
OwnerType string
}
现在您可以正常创建记录:
cust := Customer{
Title: "Cust",
Rel: Relation{Foo: "bar"},
}
comp := Company{
Title: "Comp",
Rel: Relation{Foo: "baz"},
}
db.Create(&cust)
db.Create(&comp)
要运行一个查询来获取 Customer 或 Company 以及@TehSphinX 的前两个查询中的相关信息,您可以执行以下操作:
var cust Customer
db.Joins("Rel").First(&cust, 1)
最后一个查询会更复杂,但也可以使用自定义行结构和连接来完成:
var rows []struct {
Relation
Customer Customer `gorm:"embedded;embeddedPrefix:cust_"`
Company Company `gorm:"embedded;embeddedPrefix:comp_"`
}

db.Select(`
relations.*,
customers.id AS cust_id,
customers.title AS cust_title,
companies.id AS comp_id,
companies.title AS comp_title
`).
Model(&Relation{}).
Joins("LEFT JOIN customers ON relations.owner_id = customers.id AND relations.owner_type = 'customers'").
Joins("LEFT JOIN companies ON relations.owner_id = companies.id AND relations.owner_type = 'companies'").
Find(&rows)

// now rows[i].Relation is filled, and rows[i].Customer or rows[i].Company
// are non-zero depending on rows[i].Relation.OwnerType

关于go - 我应该如何用一个外键引用两个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65357752/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com