登录
首页 >  Golang >  Go问答

GORM 外键插入方式避免使用 create

来源:stackoverflow

时间:2024-02-23 18:57:25 300浏览 收藏

大家好,今天本人给大家带来文章《GORM 外键插入方式避免使用 create》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

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


解决方案


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

本篇关于《GORM 外键插入方式避免使用 create》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>