Golang GORM无效的关联

huangapple go评论90阅读模式
英文:

Golang GORM invalid association

问题

我正在尝试使用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 [],并且在对zipcode进行查找时不会加载state。GORM是否不支持非Id主键,或者我漏掉了什么?

英文:

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

得分: 0

根据你当前的代码:

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

你没有给zc变量设置任何值,这就是为什么你会得到一个invalid association []的错误,因为数据为空。

要解决这个问题,你需要从数据库中获取ZipCode的数据,例如:

db.First(&zc, 1) // 查找id为1的ZipCode

然后你可以关联zc,完整的代码如下:

var zc ZipCode
var s State

db.First(&zc, 1) // 查找id为1的ZipCode
db.Model(&zc).Related(&s)

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

英文:

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.

huangapple
  • 本文由 发表于 2017年5月19日 02:31:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/44055396.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定