-
摇曳的蔷薇
要执行级联排除,您必须在表之间添加外键。这是我使用的一个示例,其中任务历史记录与任务相关联。当我删除任务时,它已经删除了历史记录。添加外键// 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。我希望它会有所帮助:)