协会不使用测试条目 [英] Associations not working with test entries

查看:139
本文介绍了协会不使用测试条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在GORM中定义了两个模型User和Address:档案user.go

I have two models User and Address in GORM defined: File user.go

type User struct {
    gorm.Model
    Identity     string    `json:"identity"`
    Password     string    `json:"password"`
    Address      Address
    AddressID    int
}

type Address struct {
    gorm.Model
    Street       string `json:"street"`
    StreetNumber string `json:"streetnumber"`
}

在main.go文件中,我启动数据库,自动迁移并想向数据库添加测试用户:

In the main.go file I initiate the DB, automigrate and want to add a test user to the DB:

database.InitDatabase()

database.DBConn.AutoMigrate(&user.User{})
database.DBConn.AutoMigrate(&user.Address{})

userRec := &user.User{ Identity: "John Wayne", Password: "mysecretpassword", Address: user.Address{Street: "Teststreet", StreetNumber: "1"}}

database.DBConn.Create(userRec)

也将创建用户和地址,但是,该地址与该用户没有关联,只是空的地址字段出现.我忘记了什么?

The user gets created and the address as well, however, the address is not associated with the user, just empty Address fields come up. What did I forget?

如果您的实体中有关联(使用嵌套模型),这是设置测试条目的正常方法吗?

Is this the normal way to setup a test entry if you have associations in your entities (with nested models)?

推荐答案

尝试使用"address_id"字段作为 foreignKey .

Try using the "address_id" field as a foreignKey.

例如

type User struct {
    gorm.Model
    Identity     string     `json:"identity"`
    Password     string     `json:"password"`
    Address      Address    `gorm:"foreignKey:address_id;association_autoupdate:false"`
    AddressID    uint       `json:"address_id"`
}

在线文档

也许会有所帮助.

这篇关于协会不使用测试条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆