Golang gorm update associations to save

Is there a way to automatically remove associations when saving an object?

something like that:

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 found some tricks with db.Model (& Parent) .Association ("Children"). Clear (), but this just sets the ParentID to NULL, rather than deleting the record. Is there an easy way to do this?

Thank you very much in advance:)

+4
source share

Source: https://habr.com/ru/post/1684143/


All Articles