第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

GORM 不使用 create 插入外鍵

GORM 不使用 create 插入外鍵

Go
catspeake 2022-06-21 10:54:42
我遇到了 Go 的 GORM 問題。當(dāng)我嘗試將實體保存到其中包含模型的數(shù)據(jù)庫時,它不會將外鍵與所有者模型一起保存。下面是我的模型、MySQL 腳本以及我將模型保存/創(chuàng)建到數(shù)據(jù)庫中的方式。我得到的錯誤是:字段'business_industry_id'沒有默認(rèn)值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 屬性,讓框架自己解決,但我得到了同樣的錯誤。當(dāng)我檢查模型時,行業(yè)的 id 為 3(因為我之前自己解決了它),在我保存后,ID 為 0。但是當(dāng)我刪除屬性時,保存后的 id 也是 3,但發(fā)生了同樣的錯誤。我知道錯誤消息的含義,因為記錄的 sql 消息實際上并未將 3 插入 business_industry_id 字段。我不知道的是,為什么它不插入它。
查看完整描述

1 回答

?
侃侃無極

TA貢獻(xiàn)2051條經(jīng)驗 獲得超10個贊

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


查看完整回答
反對 回復(fù) 2022-06-21
  • 1 回答
  • 0 關(guān)注
  • 233 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號