gorm关联模型定义注意事项

1.定义belongs to 关联时,如果表主键名不是ID,需要指定主键列,否则预加载查询时不会报错,但查询语句会出

type User struct {
	UserId     int        `gorm:"column:user_id;primaryKey"`
	UserName   string     `gorm:"column:user_name"`
	Company    Company    `gorm:"foreignKey:CompanyId"`
}

type Company struct {
	CompanyId   int    `gorm:"column:company_id;primaryKey"` // 需要指定主键列,否则预加载查询语句会出问题
	CompanyName string `gorm:"column:company_name"`
}

2.定义has one/has many关联时,如果两个表的关联列名对应的字段名称相同,可通过同时定义"references"和"foreignKey",进行处理,否则预加载查询语句会出错

type User struct {
	UserId     int        `gorm:"column:user_id;primaryKey"`
	UserName   string     `gorm:"column:user_name"`
	Company    Company    `gorm:"foreignKey:CompanyId"`
	CreditCard CreditCard `gorm:"references:UserId;foreignKey:UserId"`  // 同时定义"references"和"foreignKey"
}

type CreditCard struct {
	CreditId int    `gorm:"column:credit_id;primaryKey"`
	CreditNo string `gorm:"column:credit_no"`
	UserId   int    `gorm:"column:user_id"`
}

  

 

posted @ 2021-02-22 14:54  longbaobaozhiguang  阅读(276)  评论(0)    收藏  举报