Golang GORM 无效关联

Golang GORM invalid association

我正在尝试编写一个非常简单的 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 [] 错误。

要解决此问题,您必须从数据库中获取 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)

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