【问题标题】:GORM not inserting foreign key with createGORM 不使用 create 插入外键
【发布时间】:2020-07-31 03:58:56
【问题描述】:

我在使用 Go 的 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 字段。我不知道的是,为什么它不插入它。

【问题讨论】:

    标签: go go-gorm


    【解决方案1】:

    我相当肯定你必须包含外键,你不能只拥有关联的模型(参见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"`
    } 
    

    【讨论】:

    • 我将该行添加到代码中,然后再次尝试。它给了我另一个关于无法编辑孩子的错误。我检查了业务 ID 为 0。所以我删除了 gorm:"foreignkey:id" 并再次尝试并保存了记录。为什么我指定外键时它不起作用?我在那里也做错了什么?
    • 我想我应该添加 Association_foreignkey 才能正常工作?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-11
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    • 1970-01-01
    • 2013-11-03
    • 1970-01-01
    相关资源
    最近更新 更多