我遇到了 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"`
}
- 1 回答
- 0 關(guān)注
- 233 瀏覽
添加回答
舉報
0/150
提交
取消