gpt4 book ai didi

Golang GORM 无效关联

转载 作者:IT王子 更新时间:2023-10-29 01:44:45 26 4
gpt4 key购买 nike

我正在尝试编写一个非常简单的 belongsTo 与 GORM 的关联,但主键不是 Id。

我的结构是这样的:

type State struct {
FIPS string `gorm:"type:char(2);primary_key;column:FIPS"`
Name string `gorm:"not null"`
Area float64 `gorm:"type:real;not null"`
}

type ZipCode struct {
ZipCode string `gorm:"type:char(5);primary_key;"`
Name string `gorm:"not null"`
State State `gorm:"ForeignKey:StateFIPS;AssociationForeignKey:FIPS"`
StateFIPS string `gorm:"type:char(2);column:state_FIPS;not null"`
}

并使用以下代码:

var zc ZipCode
var s State
db.Model(&zc).Related(&s)

我收到错误:[2017-05-18 14:26:13] invalid association [] 并且在邮政编码上查找不会加载状态。 GORM 不喜欢非 Id 主键还是我遗漏了什么?

最佳答案

使用您当前的代码:

var zc ZipCode
var s State
db.Model(&zc).Related(&s)

您没有为您的 zc 变量设置任何内容。所以这就是为什么你会得到一个错误的 invalid association [] with an empty data。

要解决此问题,您必须从数据库中获取 ZipCode 数据,例如:

db.First(&zc, 1) // find ZipCode with id 1.

然后您可以关联您的 zc 完整代码为:

var zc ZipCode
var s State

db.First(&zc, 1) // find ZipCode with id 1.
db.Model(&zc).Related(&s)

注意:我没有测试这个实际代码,但我认为它可以解决问题。

关于Golang GORM 无效关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44055396/

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