go - GORM不使用create插入外键

标签 go go-gorm

我在Go's GORM上遇到问题。当我尝试将实体保存到内部带有模型的数据库时,它不会使用所有者模型保存外键。
以下是我的模型,MySQL脚本以及将模型保存/创建到数据库中的方式。
我收到的错误是:字段'business_industry_id'没有默认值

type Business struct {
    gorm.Model
    BusinessName       string     `json:"BusinessName"       binding:"required"  gorm:"column:business_name;type:varchar(100);unique;not null"`
    BusinessIndustry   Industry   `json:"BusinessIndustry"   binding:"required"  gorm:"foreignkey:id"`
} 

type Industry struct {
    gorm.Model
    Name string `json:"Name" gorm:"column:name;type:varchar(100);unique;not null"`
}
CREATE TABLE `industries`
(
    id         INT(6) AUTO_INCREMENT,
    name       VARCHAR(100) UNIQUE NOT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT current_timestamp,
    deleted_at TIMESTAMP,
    updated_at TIMESTAMP,
    PRIMARY KEY (id)
);

CREATE TABLE `businesses`
(
    id                             INT(6) AUTO_INCREMENT,
    business_name                  VARCHAR(100) NOT NULL UNIQUE,
    business_industry_id           INT(6) NOT NULL,
    created_at TIMESTAMP           NOT NULL DEFAULT current_timestamp,
    deleted_at TIMESTAMP,
    updated_at TIMESTAMP,
    PRIMARY KEY (id),
    FOREIGN KEY (business_industry_id) REFERENCES industries (id)
);
err := bs.database.Create(business).Error
我尝试从模型中删除Grom属性,以使框架自行解决,但出现了同样的错误。
当我检查模型时,行业的ID为3(因为我早先自己解决了该问题),并且保存后,ID为0。
但是,当我删除属性时,保存后ID也为3,但是发生了相同的错误。
我知道错误消息的含义,因为记录的sql消息实际上并未将3插入到business_industry_id字段中。我不知道的是,为什么不插入它。

最佳答案

我相当确定您必须包括外键,您不能仅具有关联的模型(请参阅http://gorm.io/docs/has_many.html)。因此,您需要执行以下操作:

type Business struct {
    gorm.Model
    BusinessName       string     `json:"BusinessName"       binding:"required"  gorm:"column:business_name;type:varchar(100);unique;not null"`
    BusinessIndustryID uint
    BusinessIndustry   Industry   `json:"BusinessIndustry"   binding:"required"  gorm:"foreignkey:id"`
} 

关于go - GORM不使用create插入外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63179842/

相关文章:

postgresql - 在 api 响应中返回 postgres 错误

json - Golang转换JSON

go - 协会不使用测试条目

go - 使用 GORM 从 Postgresql 检索表名称

go - Go中的嵌套 map

go - 如何以惯用方式构建现有包的扩展

依赖模块的Golang DDD实现

postgresql - 如何进行多对多查找查询

json - 如何将 JSON 文档中的字符串值解码为 int 类型的变量?

Go scanner - 空格的正确性?