GORM: 无法插入到生成列中。

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

GORM: cannot INSERT into generated column

问题

我在使用GORM时遇到了生成列值的问题。

我的结构体
type Product struct {
	gorm.Model

	Name     string  `json:"name" gorm:"not null"`
	Quantity uint    `json:"quantity" gorm:"not null"`
	Price    float64 `json:"price" gorm:"not null"`
	Gain     float64 `json:"gain" gorm:"not null"`

	Total     float64 `json:"total" gorm:"->;type:GENERATED ALWAYS AS (quantity*price);"`     // 生成的总价格
	TotalGain float64 `json:"total_gain" gorm:"->;type:GENERATED ALWAYS AS (quantity*gain);"` // 生成的总收益

	ProcessID uint // 一对多关系
}
自动迁移
	err = database.AutoMigrate(&models.Process{}, &models.Product{})
	if err != nil {
		return err
	}

这是错误信息

无法插入到生成列 "total"

[0.021ms] [rows:0] INSERT INTO `products__temp`(`id`,`created_at`,`updated_at`,`deleted_at`,`name`,`quantity`,`price`,`gain`,`total`,`total_gain`,`process_id`) SELECT `id`,`created_at`,`updated_at`,`deleted_at`,`name`,`quantity`,`price`,`gain`,`total`,`total_gain`,`process_id` FROM `products`

看起来GORM创建了一个临时表 "products__temp",它是 "products" 表的一个克隆。
因此,我们无法插入或编辑生成的列!

注意:我正在使用SQLite。

英文:

i have an issue with the generated columns value with GORM.

My struct
type Product struct {
	gorm.Model

	Name     string  `json:"name" gorm:"not null"`
	Quantity uint    `json:"quantity" gorm:"not null"`
	Price    float64 `json:"price" gorm:"not null"`
	Gain     float64 `json:"gain" gorm:"not null"`

	Total     float64 `json:"total" gorm:"->;type:GENERATED ALWAYS AS (quantity*price);"`     // generated total price
	TotalGain float64 `json:"total_gain" gorm:"->;type:GENERATED ALWAYS AS (quantity*gain);"` // generated total gain

	ProcessID uint // one-to-many
}
auto migration
	err = database.AutoMigrate(&models.Process{}, &models.Product{})
	if err != nil {
		return err
	}

This is the error

cannot INSERT into generated column "total"

[0.021ms] [rows:0] INSERT INTO `products__temp`(`id`,`created_at`,`updated_at`,`deleted_at`,`name`,`quantity`,`price`,`gain`,`total`,`total_gain`,`process_id`) SELECT `id`,`created_at`,`updated_at`,`deleted_at`,`name`,`quantity`,`price`,`gain`,`total`,`total_gain`,`process_id` FROM `products`

It seems like GORM has created a temporary table "products__temp" a clone of "products" table.
So as we can know we cannot insert or edit the generated columns!

> Note: i'm working wih SQLite

答案1

得分: 2

这个问题已经通过我的拉取请求解决了。

https://github.com/go-gorm/sqlite/pull/109

这个拉取请求已经被接受了。👍🏻

英文:

This issue is fixed by my pull request

https://github.com/go-gorm/sqlite/pull/109

the pull is accepted 👌🏻

huangapple
  • 本文由 发表于 2022年8月9日 10:45:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/73286022.html
匿名

发表评论

匿名网友

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

确定