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 要写结构体关联字段的名称,不要写数据表名称,或者关联模型结构体的名称
posted @ 2023-07-06 18:44  TaylorSWMM  阅读(1250)  评论(1编辑  收藏  举报