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 要寫結構體關聯字段的名稱,不要寫數據表名稱,或者關聯模型結構體的名稱
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章