与一对多的关联无效



我有以下结构

type Store struct {
StoreID   int    `gorm:"primary_key;AUTO_INCREMENT;not null"`
Name      string `gorm:"not null"`
Adress    string `gorm:"not null"`
Manager   User   `gorm:"not null"`
ManagerID int    `gorm:"foreignkey:ManagerID;not null"`
Boxes     []Box
}
type Box struct {
BoxID       int `gorm:"primary_key;AUTO_INCREMENT;not null"`
StoreID     int `gorm:"not null"`
Items       []Item
Code        int    `gorm:"type:integer(13)"`
Description string `gorm:"not null"`
}
func (s *Store) AddBox(b Box) error {
err := db.Model(&s).Association("Boxes").Append(&b)
return err.Error
}

我正在对所述结构及其功能进行测试。其中一个测试看起来像这样

func TestStoreAddBox(t *testing.T) {
b := Box{BoxID: 1}
err := b.GetDetails()
if err != nil {
t.Errorf("Expected no #1 error but got %v", err)
}
s := Store{StoreID: 2}
err = s.GetDetails()
if err != nil {
t.Errorf("Expected no #2 error but got %v", err)
}
err = s.AddBox(b)
if err != nil {
t.Errorf("Expected no #3 error but got %v", err)
}
}

现在,如果我开始测试,则会出现以下错误:

--- FAIL: TestStoreAddBox (0.00s)
db100_test.go:371: Expected no #3 error but got invalid association Boxes for db100.Store

有谁知道这里的问题是什么?

好的,结果踢球者是 GORM 文档中的以下句子:

要定义具有许多相关性,外键必须存在,默认外键的名称是所有者的类型名称加上其主键。

所以就我而言,这将是

商店

商店ID

所以我不得不更改商店结构虱子

type Store struct {
StoreID   int    `gorm:"primary_key;AUTO_INCREMENT;not null"`
Name      string `gorm:"not null"`
Adress    string `gorm:"not null"`
Manager   User   `gorm:"not null"`
ManagerID int    `gorm:"foreignkey:ManagerID;not null"`
Boxes     []Box  `gorm:"foreignkey:StoreID;association_foreignkey:StoreID"`
}

最新更新