Pg: Cascading inserts and deletes

Created on 19 Sep 2016  路  7Comments  路  Source: go-pg/pg

If I have the following model:

book := Book{
    ID: 0,
    Name: "Slaughterhouse 5",
    Author: &Author{
        ID: 0,
        Name: "Vonnegut, Kurt",
    },
}

I would like to call db.Create(&book) and have it create both a new Book record and create the embedded Author record. Is this possible with a single call?

Most helpful comment

I was thinking about db.InsertCascade or probably adding Save and SaveCascade. Also let's keep this issue open so we have only 1 copy of it.

All 7 comments

No, currently there is no any way to achieve this. I doubt it is going to be added any time soon because there are more important/interesting tasks :)

In that case, it seems models with one-to-many relationships would require multiple for-loops to manually go through and save each model.

Example:

_ = db.Create(&author)

for _, book := range author.Books {
    book.AuthorID = author.ID
    _ = db.Create(&book)

    for _, tag := range book.Tags {
        tag.BookID = book.ID
        _ = db.Create(&tag)

        // ... etc.
    }
}

Perhaps as a suggestion for future, if someone wanted to add this feature, a tag on the struct would make this more straightforward.

type Author struct {
    // ... other properties
    Books []Book `pg:",cascade"`
}

I was thinking about db.InsertCascade or probably adding Save and SaveCascade. Also let's keep this issue open so we have only 1 copy of it.

Any update?

No, I hope it will be done eventually but it is not a priority (at least for me).

Updates?

Thanks for creating a great lib! Are there any updates to these cascading capabilities?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

l0gicgate picture l0gicgate  路  5Comments

rhymes picture rhymes  路  5Comments

pahanini picture pahanini  路  4Comments

sas1024 picture sas1024  路  5Comments

mamal72 picture mamal72  路  3Comments