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