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

GORM CreateInBatches with embedded structure error

WBOY
Release: 2024-02-05 21:27:12
forward
831 people have browsed it

带有嵌入式结构错误的 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"`
}
Copy after login

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

type user struct {
    id         int
    userid     int
    isactive   bool 
}
Copy after login

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
    }
}
Copy after login

For completeness, here are the errors:

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

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"`
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template