猿问

如何使用 GORM (Go) 处理级联操作

我正在测试 Go 的 GORM 库。我发现这个库特别有用,并且我一步一步地处理越来越复杂的概念。

我面临着级联运营管理的问题。

在某些问题上,创建者建议使用 AfterDelete。问题是:在 After/BeforeDelete 函数中,不存在嵌套项。

每个人都有实现这个的好方法吗?


慕码人2483693
浏览 252回答 3
3回答

摇曳的蔷薇

要执行级联排除,您必须在表之间添加外键。这是我使用的一个示例,其中任务历史记录与任务相关联。当我删除任务时,它已经删除了历史记录。添加外键// Add foreign key// 1st param : foreignkey field// 2nd param : destination table(id)// 3rd param : ONDELETE// 4th param : ONUPDATEdb.Model(&User{}).AddForeignKey("city_id", "cities(id)", "RESTRICT", "RESTRICT")我的例子:db.Model(&models.TaskHistoric{}).AddForeignKey("task_uuid", "tasks(uuid)", "CASCADE", "CASCADE")

qq_笑_17

type Bucketlist struct {    gorm.Model    Name      string           `json:"name"`    CreatedBy string           `json:"created_by"`    UserID    uint             `json:"user_id"`    Item      []BucketlistItem `json:"item"`}type BucketlistItem struct {    gorm.Model    Name         string `json:"name"`    Done         bool   `json:"done"`    BucketlistID uint   `json:"bucketlist_id,omitempty"`}// AfterDelete hook defined for cascade deletefunc (bucketlist *Bucketlist) AfterDelete(tx *gorm.DB) error {    return tx.Model(&BucketlistItem{}).Where("bucketlist_id = ?", bucketlist.ID).Unscoped().Delete(&BucketlistItem{}).Error}这对我有用上下文:当删除桶列表模型实例时,相应的项目(1 到 x)也使用 AfterDelete 钩子删除。

MMMHUHU

我已经实施了这个解决方案来响应我的问题:func DeleteContentCascade(content *Content, db *gorm.DB, debug bool) error {  if debug {      db = db.Debug()  }  for _, child := range content.Children {      DeleteChildCascade(&child, db, debug) //Custom method like the current  }  if err := db.Delete(content).Error; err != nil {      return err  }  return nil}对于数据库管理中的每个“项目”文件,我都创建了一个自定义函数 DeleteCascade。我希望它会有所帮助:)
随时随地看视频慕课网APP

相关分类

Go
我要回答