GORM使用嵌入结构的CreateInBatches时出现错误。

huangapple go评论80阅读模式
英文:

GORM CreateInBatches with Embedded Struct Error

问题

我有以下的结构体(为了可读性而截断):

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

type User struct {
    ID       int
    UserId   int
    IsActive bool
}

我正在尝试对Schedule结构体(作为[]Schedule)执行CreateInBatches操作。但是当我这样做时,插入查询也会尝试插入User结构体的值。

以下是部分插入代码示例:

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

为了完整起见,这是错误信息:

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

有没有标签或其他方法可以在插入查询中省略User结构体?当我输出查询时,它显示为:

INSERT INTO schedule (schedule columns..., [additional user struct columns])

我还尝试了文档中的字段权限标签这里的方法。

英文:

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

答案1

得分: 1

问题在于你在Schedule结构体内部使用了embedded标签来表示User。当你将其移除后,它应该按预期工作。你可以在文档中了解更多信息。

所以你的Schedule结构体应该像这样:

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

请注意,我已经将代码部分翻译为中文,如果你还有其他问题,请继续提问。

英文:

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"`
}

huangapple
  • 本文由 发表于 2023年4月6日 04:07:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75943586.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定