【问题标题】:golang gorm update associations on savegolang gorm 在保存时更新关联
【发布时间】:2018-01-29 20:25:51
【问题描述】:

有没有办法在保存对象时自动删除关联?

类似这样的:

type Parent struct {
    gorm.Model
    Name string
    Children []*Child
}

type Child struct {
    gorm.Model
    Name string
    ParentID uint
}

func myFunc(db *gorm.DB) {
    p := &Parent{Name: "foo", Children:[]*Child{ {Name:"Bar"}, {Name:"Foobar"}}}
    db.Save(&p)

    p.Children = p.Children[1:]
    db.Save(&p)  // both children still exist in the database. i'd like the first child to be deleted here
}

`

我发现了 db.Model(&Parent).Association("Children").Clear() 的一些技巧,但这只是将 ParentID 值设置为 NULL,而不是删除记录。有没有一种简单的方法可以做到这一点?

提前非常感谢:)

【问题讨论】:

  • 嗨,你找到答案了吗?我在这里面临同样的问题......
  • 是的,可以使用它的映射键值删除子节点
  • @muthukumarselvaraj 你会怎么做?您能否将其发布为答案。当前答案仅硬删除而不是软删除。

标签: go go-gorm


【解决方案1】:

我认为你只是简单地使用物理批量删除,如下代码:

db.Unscoped().Where("parent_id = ?", p.ID).Delete(Child{})

希望对您有所帮助。

【讨论】:

  • 这将硬删除记录
猜你喜欢
  • 1970-01-01
  • 2015-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-07
  • 2021-10-12
  • 2021-10-16
相关资源
最近更新 更多