Golang GORM无效关联

时间:2017-05-18 18:31:28

标签: go go-gorm

我正在尝试使用GORM编写一个非常简单的belongsTo关联,但主键不是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主键还是我错过了什么?

1 个答案:

答案 0 :(得分:0)

使用您当前的代码:

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)

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