1 回答
TA贡献1752条经验 获得超4个赞
我找到了一个解决方案,但我认为它不是级联删除的最佳选择,它至少解决了我的问题。我编写了以下内容:
首先是函数,我循环访问所有函数并调用函数,最后在删除项目之前清除与此项目的所有关联。DeleteProjectDiagramsDeleteDiagram
//Delete a project and it's associations.
func DeleteProject(db *gorm.DB, id uint) (Project, error) {
project, err := GetProject(db, id)
if err != nil {
return Project{}, err
}
if len(project.Diagrams) > 0 {
for _, projectDiagram := range project.Diagrams {
_, err := DeleteDiagram(db, projectDiagram.ID)
if err != nil {
return Project{}, err
}
}
db.Model(&project).Association("Diagrams").Clear()
}
if err := db.Delete(&project, id).Error; err != nil {
return Project{}, err
}
return project, nil
}
做同样的事情,但随后与DeleteDiagramInstances
//Delete a diagram and it's associations.
func DeleteDiagram(db *gorm.DB, id uint) (Diagram, error) {
var diagram, err = GetDiagram(db, id)
if err != nil {
return Diagram{}, err
}
if len(diagram.Instances) > 0 {
db.Model(&diagram).Association("Instances").Clear()
for _, diagramInstance := range diagram.Instances {
_, err := DeleteInstance(db, diagramInstance.ID)
if err != nil {
return Diagram{}, err
}
}
}
if err := db.Delete(&diagram).Error; err != nil {
return Diagram{}, err
}
return diagram, nil
}
希望它有帮助。
- 1 回答
- 0 关注
- 314 浏览
添加回答
举报