Gorm – 更新模型并将其添加到切片中

huangapple go评论89阅读模式
英文:

Gorm - Updating model and appending to a slice

问题

我正在使用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
        // 查找博客文章
        if err := models.DB.Where("id = ?", parentId).First(&blogPost).Error; err != nil {
            return
        }
        // 将评论添加为博客文章的评论
        comment := &models.Comment{
            ParentId:    parentId,
            ParentType:  PT_BlogPost,
            Author:      "",
            Content:     "",
            SubComments: nil,
        }
        models.DB.Create(&comment)

        // TODO 在这里添加评论时出错
        blogPost.Comments = append(blogPost.Comments, comment)

        // TODO 如何使用gorm更新BlogPost
        models.DB.Model(&blogPost).Updates(blogPost)

    }
}

以上是你提供的代码的翻译。

英文:

I'm using gorm and have some questions as to how to update the model. I'm getting an error trying to append &Comment to BlogPost struct. Also trying to figure out how to persist the updated BlogPost to DB.

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)

	}
}

答案1

得分: 1

你可以使用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
        // 查找博客文章
        if err := models.DB.Where("id = ?", parentId).First(&blogPost).Error; err != nil {
            return
        }

        // 将评论添加为博客文章的评论
        comment := &models.Comment{
            ParentId:    parentId,
            ParentType:  PT_BlogPost,
            Author:      "",
            Content:     "",
            SubComments: nil,
        }

        // TODO 在这里添加评论时出错
        blogPost.Comments = append(blogPost.Comments, comment)

        // TODO 如何使用gorm更新BlogPost
        models.DB.Session(&gorm.Session{FullSaveAssociations: true}).Model(&blogPost).Updates(blogPost)

    }

}

FullSaveAssociations: true选项类似于upsert函数。如果你想要更新/创建关联关系,可以使用这个选项。此外,你应该为Comments模型使用references和foreignkey。gorm:"foreignKey:parent_id;references:id"

如果你想获取更多信息,可以查看下面的链接:

https://gorm.io/docs/associations.html#Auto-Create-Update

英文:

You can use gorm.Session attribute.

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 option works like upsert function. if you wanna update/create with relation, you can use this. also you should to use references and foreignkey for Comments model. gorm:"foreignKey:parent_id;references:id".

if you want to get more information you can look below link;

https://gorm.io/docs/associations.html#Auto-Create-Update

huangapple
  • 本文由 发表于 2022年4月24日 02:36:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/71982627.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定