在保存时更新关联的Golang GORM代码

huangapple go评论94阅读模式
英文:

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 在保存时更新关联的Golang GORM代码

答案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.

huangapple
  • 本文由 发表于 2017年8月22日 01:19:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/45802577.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定