Reputation: 11
I am new to Golang and I am trying to bulk update models for a table.
I have a "owners" table where I am trying to update multiple rows. my go model (not complete):
type Owners struct {
OwnerID int64 `gorm:"primaryKey;not null"`
OwnerName string
Eligibility bool
}
I have a logic that updated the Eligibility to true or false for multiple rows
Using Python SQLAlchemy, I can create a session and use add_all() method to bulk update the rows. Is there something similar on GORM.
I tried the following code
const batchSize = 100
func bulkUpdate(owners *[]Owners) {
for i := 0; i < len(*owners); i += batchSize {
end := i + batchSize
if end > len(*owners) {
end = len(*owners)
}
batch := (*owners)[i:end]
log.Println("batch=", len(batch))
//result := config.DB.Table("owners").Updates(batch)
result := config.DB.Model(owners).Updates(batch)
log.Println("result=", result)
if result.Error != nil {
log.Println(result.Error)
}
}
config.DB.Commit()
}
But this gives me error "unsupported data"
I can do the following, which works fine:
for _, ownership := range owners {
config.DB.Save(&ownership)
}
but since I have 4000+ rows, it takes lot of time.
Upvotes: 1
Views: 105
Reputation: 781
I'm still pretty new to Go and Gorm but I do not believe there is a similar function to the add.all() function in SQLAlchemy.
For GORM I believe you have to use the Create() method with a slice of structs as input which will insert multiple records in a single transaction. Though that may not be exactly what you're looking for :).
Upvotes: 0