Home  >  Article  >  Backend Development  >  GORM CreateInBatches with embedded structure error

GORM CreateInBatches with embedded structure error

WBOY
WBOYforward
2024-02-05 21:27:12732browse

带有嵌入式结构错误的 GORM CreateInBatches

Question content

I have the following structure (truncated for readability)

type schedule struct {
    id              int  
    userid          int
    user            user    `gorm:"embedded;foreignkey:userid;references:userid"`
}

Then here is my user structure (again truncated for readability):

type user struct {
    id         int
    userid     int
    isactive   bool 
}

I'm trying createinbatches on a schedule structure (like []schedule ). But when I do this, the insert query also tries to insert the value from the user structure.

Insert example (part of the code):

err := db.transaction(func(tx *gorm.db) error {
    if err := tx.createinbatches(&schedules, len(schedules)).error; err != nil {
        return err //rollback
    }
}

For completeness, here are the errors:

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

Is there a tag or anything I can do to omit the user structure from the insert query? When I output the query it shows insert into schedule (schedule column..., [additional user structure column])

I also tried the field permission tags based on the documentation here


Correct answer


The problem is that you are # in the schedule structure ##user Use the embedded tag. When you remove it it should work as expected. You can read related content in Documentation

So your

schedule structure should look like this:

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

The above is the detailed content of GORM CreateInBatches with embedded structure error. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete