-
-
Notifications
You must be signed in to change notification settings - Fork 4.1k
Description
I am working with objects that have a one-to-many relationship as follows:
type Parent struct {
ID string `gorm:"primaryKey;column:parent_id"`
ChildList []Child `gorm:"foreignKey:ParentID;references:ID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"`
}
type Child struct {
ID string `gorm:"primaryKey;column:child_id"`
ParentID string `gorm:"column:parent_id"`
}
First I create and then save parent object like this:
newParent := &Parent{
ID: uuid.New().String(),
}
tx.Model(&Parent{}).Create(&newParent)
Then I create some child objects to add to the parent:
newChild1 := &Child{
ID: uuid.New().String(),
}
newChild2 := &Child{
ID: uuid.New().String(),
}
newParent.ChildList = []Child{
*newChild1,
*newChild2,
}
Here's what I expected to work, which fails
tx.CreateInBatches(newParent.ChildList, 16000)
When saving with this method the value for ParentID is not set on the child objects. Depending on how the table was created you either get null / empty values for the parent_id column or an error that the constraint has been violated.
If you simply call the following it does work, but that doesn't help with our batching:
tx.Save(&newParent)
I am able to work around this by adding the IDs manually before the call to CreateInBatches:
for idx, child := range newParent.ChildList {
child.ParentID = newParent.ID
newParent.ChildList[idx] = child
}
My question is: Is this by design, or is there some bug that's causing this association to not save properly, or am I using it incorrectly?