英文:
golang gorm update associations on save
问题
当对象保存时,有没有一种自动删除关联的方法?
像这样:
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) // 数据库中仍然存在两个子对象。我希望在这里删除第一个子对象
}
我找到了一些使用 db.Model(&Parent).Association("Children").Clear()
的技巧,但这只会将 ParentID 的值设置为 NULL,而不是删除记录。有没有简单的方法可以做到这一点?
非常感谢!
英文:
is there a way to automatically remove associations when an object is saved?
something like this:
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
}
`
I've found some tricks with db.Model(&Parent).Association("Children").Clear(), but that just sets the ParentID value to NULL, rather than deleting the record. Is there a simple way of doing this?
Many thanks in advance
答案1
得分: 1
我认为你只需要简单地使用物理批量删除,就像下面的代码一样:
db.Unscoped().Where("parent_id = ?", p.ID).Delete(Child{})
希望这对你有帮助。
英文:
I think you just simply use the physical batch delete like following code:
db.Unscoped().Where("parent_id = ?", p.ID).Delete(Child{})
Hope this help.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论