本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《如何用GORM获取相关数据?》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~
问题内容我想从其他表获取相关数据
我有以下模型结构
type community struct {
id string `json:"id" gorm:"primarykey"`
name string `json:"name"`
category communitycategory `json:"category" gorm:"foreignkey:id"`
}
type communitycategory struct {
id uint32 `json:"id" gorm:"primarykey"`
name string `json:"name"`
}
我获取数据的代码是这样的
community := community{id: 1}
database.debug().joins("communitycategory").first(&community)
有了这些,我收到以下错误 error:对表“communities”(sqlstate 42p01)
的 from 子句条目的引用无效
查看gorm的调试日志,查询是这样的
SELECT "communities"."id","communities"."name","communities"."introduction","communities"."address","communities"."postal_code","communities"."country","communities"."address1","communities"."address2","communities"."prefecture","communities"."city","communities"."lat","communities"."lng","communities"."phone","communities"."email","communities"."external_link_1","communities"."external_link_2","communities"."image_url","communities"."access","communities"."description","communities"."contact_name","communities"."contact_phone","communities"."contact_email","communities"."is_enabled","communities"."created_at","communities"."updated_at" FROM "communities" CommunityCategory WHERE "communities"."id" = '25b1eadf-1004-40b7-b9a2-325a83bcb938' ORDER BY "communities"."id" LIMIT 1
我做错了吗?哈哈
解决方案
通过按如下方式定义我的结构来修复此问题。我在 community
结构中添加了一个新字段 categoryid
并将外键更改为这个新字段
type community struct {
id string `json:"id" gorm:"primarykey"`
name string `json:"name"`
categoryid uint32
category communitycategory `json:"category" gorm:"foreignkey:categoryid"`
}
type communitycategory struct {
id uint32 `json:"id" gorm:"primarykey"`
name string `json:"name"`
}
然后在查询时,您可以像这样执行连接:
community := Community{ID: 1}
database.Model(&Community{}).Joins("Category").First(&community)
到这里,我们也就讲完了《如何用GORM获取相关数据?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注编程网公众号,带你了解更多关于的知识点!