golang gorm三个表关联Preload的写法

golang gorm三个表关联Preload的写法,第1张

需求

三个表 article,article_user,user
article和article_user 是一对多
article_user 和 user 是一对一

查询一条 article的记录的时候,需要同时将 user的数据也带过来

{
  "id": 1,
  "article_users": [
    {
      "id": 100,
      "user_id": 10,
      "user": {
        "id": 10,
        "user_name": "XXX"
      }
    }
  ]
}
结构体定义
type Article struct {
	Id           int           `json:"id"`
	ArticleUsers []ArticleUser `json:"article_users"`
}

type ArticleUser struct {
	Id     int  `json:"id"`
	UserId int  `json:"user_id"`
	User   User `json:"user" gorm:"foreignKey:id;AssociationForeignKey:user_id"`
}

type ArticleUser struct {
	Id       int    `json:"id"`
	UserName string `json:"user_name"`
}
查询gorm
var model models.Article
	err = GetDB().Model(&models.Article{}).Where(id).Preload("ArticleUsers").Preload("ArticleUsers.User").Find(&model).Error
关键点 Preloadgorm的关键词 需要 foreignKey 指定外部ID,AssociationForeignKey 指定关联的本ID在Preload中可以使用点号进行指定 ArticleUsers.User

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/996312.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存