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?
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?
Most helpful comment
I was thinking about
db.InsertCascadeor probably addingSaveandSaveCascade. Also let's keep this issue open so we have only 1 copy of it.