亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

GORM 不使用 create 插入外鍵

GORM 不使用 create 插入外鍵

Go
catspeake 2022-06-21 10:54:42
我遇到了 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 字段。我不知道的是,為什么它不插入它。
查看完整描述

1 回答

?
侃侃無極

TA貢獻2051條經驗 獲得超10個贊

我相當肯定你必須包含外鍵,你不能只擁有關聯的模型(參見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"`


查看完整回答
反對 回復 2022-06-21
  • 1 回答
  • 0 關注
  • 240 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號