今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《Gorm - 更新模型并添加到列表中》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!
我正在使用 gorm,并且对如何更新模型有一些疑问。我在尝试将 &comment 附加到 blogpost 结构时遇到错误。还试图弄清楚如何将更新的 blogpost 持久保存到数据库。
type BlogPost struct {
ID uint `gorm:"primary_key"`
Content string
Comments []Comment
}
type ParentType int
const (
PT_BlogPost ParentType = 1
PT_Comment = 2
)
type Comment struct {
ID uint `gorm:"primary_key"`
ParentId uint
ParentType ParentType
Comment string
SubComments []Comment
}
func createComment(parentId uint, parentType ParentType) {
switch parentType {
case PT_BlogPost:
var blogPost BlogPost
// lookup blog post
if err := models.DB.Where("id = ?", parentId).First(&blogPost).Error; err != nil {
return
}
// add comment as comment on blog post
comment := &models.Comment{
ParentId: parentId,
ParentType: PT_BlogPost,
Author: "",
Content: "",
SubComments: nil,
}
models.DB.Create(&comment)
// TODO Error adding comment here
blogPost.Comments = append(blogPost.Comments, comment)
// TODO How to update BlogPost with gorm
models.DB.Model(&blogPost).Updates(blogPost)
}
}正确答案
您可以使用 gorm.session 属性。
type BlogPost struct {
ID uint `gorm:"primary_key"`
Content string
Comments []Comment
}
type ParentType int
const (
PT_BlogPost ParentType = 1
PT_Comment = 2
)
type Comment struct {
ID uint `gorm:"primary_key"`
ParentId uint
ParentType ParentType
Comment string
SubComments []Comment
}
func createComment(parentId uint, parentType ParentType) {
switch parentType {
case PT_BlogPost:
var blogPost BlogPost
// lookup blog post
if err := models.DB.Where("id = ?", parentId).First(&blogPost).Error; err != nil {
return
}
// add comment as comment on blog post
comment := &models.Comment{
ParentId: parentId,
ParentType: PT_BlogPost,
Author: "",
Content: "",
SubComments: nil,
}
// TODO Error adding comment here
blogPost.Comments = append(blogPost.Comments, comment)
// TODO How to update BlogPost with gorm
models.DB.Session(&gorm.Session{FullSaveAssociations: true}).Model(&blogPost).Updates(blogPost)
}
}
fullsaveassociations:true 选项的工作方式类似于 upsert 函数。如果你想更新/创建关系,你可以使用这个。您还应该对评论模型使用引用和外键。 gorm:"foreignkey:parent_id;references:id"。
如果您想获取更多信息,可以查看下面的链接;
https://gorm.io/docs/associations.html#Auto-Create-Update
今天关于《Gorm - 更新模型并添加到列表中》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
