golang: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 要写结构体关联字段的名称,不要写数据表名称,或者关联模型结构体的名称

调了半天网上没个对的,官方文档也是一笔掠过,真就浪费青春 。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值