使用"gorm.io/gen" 生成的结构体,在后来使用 "gorm.io/gorm" 还原数据库表结构时,表中的PrimaryKey缺少AutoIncrement
1、使用Mysql 建立如下数据库example, 建立如下表people:
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for people
-- ----------------------------
DROP TABLE IF EXISTS `people`;
CREATE TABLE `people` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`age` int(11) NOT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
此时表中主键有AutoIncrement标记,如下图所示,左下角的自动递增已经勾选。
2、使用"gorm.io/gen" 生成该该数据库对应的表结构
g := gen.NewGenerator(gen.Config{
ModelPkgPath: "./impl/mysql/model",
FieldNullable: true,
FieldCoverable: true,
FieldWithIndexTag: true,
FieldWithTypeTag: true,
})
db, _ := gorm.Open(mysql.Open("root:lvlv@(127.0.0.1:3306)/example?charset=utf8mb4&parseTime=True&loc=Local"))
g.UseDB(db)
g.GenerateAllTable()
运行后生成的数据库表结构体如下:
package model
const TableNamePerson = "people"
// Person mapped from table <people>
type Person struct {
ID int32 `gorm:"column:id;type:int(20);primaryKey;autoIncrement:true" json:"id"`
Name string `gorm:"column:name;type:varchar(255);not null" json:"name"`
Age int32 `gorm:"column:age;type:int(11);not null" json:"age"`
}
// TableName Person's table name
func (*Person) TableName() string {
return TableNamePerson
}
3、编写另外一个cmd程序,利用上述生成的struct 来自动建立数据库。 先新建数据库example1,在example1中利用上步生成的struct 重建Person表结构。
dsn := "root:lvlv@(127.0.0.1:3306)/example1?charset=utf8mb4&parseTime=True&loc=Local")
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
SkipDefaultTransaction: true,
NamingStrategy: schema.NamingStrategy{SingularTable: true},
})
e = db.AutoMigrate(&model.Person{})
if e != nil {
fmt.Println("AutoMigrate error!", e)
}
此时生成的数据库example1中的表结构中对于主键id没有AutoIncrement选项。如下图所示,自动递增没有勾选。
这导致后续向该表中添加记录时,报错。
Comment From: tr1v3r
这个问题是说GORM的AutoMigrate方法没有识别同步id的autoIncrement:true?这个问题你应该首先尝试更新一下GORM的版本,而且这是一个GORM的issue,你应该在提到对应的仓库
Comment From: github-actions[bot]
The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.io ✨ Search Before Asking ✨