如果是用gorm建立(迁移)的表,它默认的表名和ID,则不需要专门去使用foreignkey和references,直接用preload来查询即可关联到。
如果是其他比如beego的orm建立的表,则要使用foreignkey和references
foreignkey是外表里的id,比如是`Id`
references是本表中的id,比如是`UserID`
// math模板表——用gorm的_db.AutoMigrate(&MathTemple{})迁移(建立)
type MathTemple struct {gorm.ModelClassID int64 `json:"classid" gorm:"column:class_id;"`Number string `json:"number"`UserID int64 `gorm:"column:user_id;`User User `gorm:"foreignkey:Id;references:UserID;"`// MathArticleID uint `gorm:"column:math_article_id;`MathArticle MathArticle
}// 用户表——用beego orm建立
type User struct {Id int64Username string `json:"name",orm:"unique"`Nickname string
}// math的文章——用gorm的_db.AutoMigrate(&MathArticle{})迁移(建立)
type MathArticle struct {gorm.ModelMathTempleID uint `json:"tempid" gorm:"column:math_temple_id"`Title string `json:"title" gorm:"column:title;size:20"`Subtext string `json:"subtext" gorm:"column:subtext;size:20"`Content string `json:"html" gorm:"column:content;size:5000"`
}
这里有好几种情况:上面mathtemple表中,User和UserID,当只有UserID而无User的时候,preload查询是查不出User表的。当只有User而无UserID的时候,例如mathtemple表中的matharticle就是不带matharticelid的,也是可以preload查出的,因为mathtemple表里对应有mathtempleid啊。如果后者表里不带mathtempleid,估计就查不出来。
还有,如果mathtemple表里的User,不写`gorm:"foreignkey:Id;references:UserID;"`,或者只写`gorm:"foreignkey:Id;"`不写`"references:UserID;"`,都无法自动迁移(automigrate)!