Go 中的多态关联如何查询
文档中只看到了多态关联的正向插入,但是对于反向的操作一直不知道怎么写
场景:有文章表和话题表,评论表中存放文章和话题的评论,一篇文章可以有多条评论,话题同样,一条评论只能关联一篇文章或者一个话题
希望结果:可以通过文章查询到该文章下所有评论,可以通过话题查询到所有评论,可以通过评论查询到话题或者文章
数据库存储数据:
models:
// 文章
type Article struct {
ID uint64 `gorm:"column:id;primaryKey;autoIncrement;" json:"id,omitempty"`
Name string `json:"name"`
Comment []Comment `gorm:"polymorphic:Owner;polymorphicValue:article;" json:"comment"`
}
func (Article) TableName() string {
return "articles"
}
// 话题
type Topic struct {
ID uint64 `gorm:"column:id;primaryKey;autoIncrement;" json:"id,omitempty"`
Name string `json:"name"`
Comment []Comment `gorm:"polymorphic:Owner;polymorphicValue:topic;" json:"comment"`
}
func (Topic) TableName() string {
return "topics"
}
// 评论 一条评论只能对应一条文章或一条话题
type Comment struct {
ID uint64 `gorm:"column:id;primaryKey;autoIncrement;" json:"id,omitempty"`
Content string `json:"content"`
OwnerType string `json:"owner_type"`
OwnerID uint64 `json:"owner_id"`
}
func (Comment) TableName() string {
return "comments"
}
文章和话题可以正确获取评论
var article []models.Article
database.DB.Preload("Comment").Find(&article)
但是从评论获取文章和话题的查询语句不知道该如何写?期间查过百度也问过GPT,但是并没有实现(也挺疑惑的,这不应该是很常见的场景吗?为啥很少这样的写法,难道go中不这样实现吗)
我是通过预加载解决问题,首先你需要声明一个对应结构存放到结构体中,让后在查询的时候使用预加载进行附带信息查询