Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang gorm update associations on save

Tags:

go

go-gorm

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 :)

like image 675
ehrt1974 Avatar asked Aug 21 '17 17:08

ehrt1974


Video Answer


1 Answers

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.

like image 194
ThanhHH Avatar answered Sep 16 '22 18:09

ThanhHH