Gorm一对一,一对多,查询报错 unsupported relations for schema
Gorm一对一,一对多,搞我半天bug
标签(空格分隔): go,gorm
问题:一对一,一对多,查询数据报错:unsupported relations for schema
代码
// GoodsSpecificationAttrModel 商品规格-属性表
type GoodsSpecificationAttrModel struct {
ID int32 `gorm:"column:id;primaryKey;autoIncrement;not null;"`
GoodsId int32 `gorm:"column:goods_id;default:0;comment:'商品id'"`
Name string `gorm:"column:name;comment:'属性名称'"`
ValueData []GoodsSpecificationAttrValueModel `gorm:"foreignKey:attr_id;references:id"`
}
func (g *GoodsSpecificationAttrModel) TableName() string {
return "goods_specification_attribute"
}
// GoodsSpecificationAttrValueModel 商品规格-属性值表
type GoodsSpecificationAttrValueModel struct {
ID int32 `gorm:"column:id;primaryKey;autoIncrement;not null;"`
GoodsId int32 `gorm:"column:goods_id;default:0;comment:'商品id'"`
AttrId int32 `gorm:"column:attr_id;default:0;comment:'属性id'"`
Name string `gorm:"column:name;comment:'属性值'"`
AttrData GoodsSpecificationAttrModel `gorm:"foreignKey:attr_id;references:id"`
}
func (g *GoodsSpecificationAttrValueModel) TableName() string {
return "goods_specification_attribute_value"
}
// 查询数据
var attrValue GoodsSpecificationAttrValueModel
tx := global.DB.Debug().Preload("AttrData").
Where("id = ?", 1).
Limit(1).
Find(&attrValue)
fmt.Printf("row: %d\n", tx.RowsAffected)
fmt.Printf("err: %+v\n", tx.Error)
fmt.Printf("res: %+v\n", attrValue)
问题原因
Preload 要写结构体关联字段的名称,不要写数据表名称,或者关联模型结构体的名称
分类:
Go
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)