Search code examples
gogo-gorm

GORM CreateInBatches with Embedded Struct Error


I have the following struct (truncated for readability)

type Schedule struct {
    ID              int  
    UserId          int
    User            User    `gorm:"embedded;foreignKey:UserId;references:UserId"`
}

And then my User struct (again, truncated for readability):

type User struct {
    ID         int
    UserId     int
    IsActive   bool 
}

I'm attempting a CreateInBatches on the Schedule struct (as []Schedule). But when I do, the insert query is attempting to also insert the values from the User struct.

Example (partial code) for insertion:

err := db.Transaction(func(tx *gorm.DB) error {
    if err := tx.CreateInBatches(&schedules, len(schedules)).Error; err != nil {
        return err //Rollback
    }
}

For completion sake, here is the error:

Error Inserting Schedule Batch: Error 1054: Unknown column 'is_active' in 'field list'

Is there a tag or anything that I can do to omit the User struct from the insert query? When I output the query, it is showing the INSERT INTO schedule (schedule columns..., [additional user struct columns])

I've also tried the field permission tags per the documentation here


Solution

  • Issue is that you are using embedded tag for User inside Schedule struct. It should work as expected when you remove it. You can read about it in docs

    So your Schedule struct should look like this:

    type Schedule struct {
        ID              int  
        UserId          int
        User            User `gorm:"foreignKey:UserId;references:UserId"`
    }