duancai1904 2017-05-18 18:31
浏览 267
已采纳

Golang GORM无效关联

I'm trying to write a very simple belongsTo association with GORM, but with primary keys that isn't Id.

My structs are as such:

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"`
}

and with the following code:

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

I get the error: [2017-05-18 14:26:13] invalid association [] and a find on the zipcode doesn't load the state. Does GORM not like non-Id primary keys or am I missing something?

  • 写回答

1条回答 默认 最新

  • dsizd368332 2017-05-19 07:46
    关注

    With your current code :

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

    You are not set anything to your zc variable. so that's why you get an error of invalid association [] with an empty data.

    To fix this you must get the ZipCode data from your database like :

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

    and then you can associate your zc full code would be :

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

    Note : I'm not testing this actual code but I think it would fix the problem.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗