golang gorm更新关联保存

时间:2017-08-21 17:19:25

标签: go go-gorm

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

类似的东西:

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,而不是删除记录。有一种简单的方法吗?

非常感谢提前:)

1 个答案:

答案 0 :(得分:0)

我认为您只需使用物理批量删除,如下面的代码:

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

希望得到这个帮助。

相关问题