简体   繁体   English

如何使用 GORM 创建表?

[英]How can I create a table using GORM?

I was trying to create a table of user using GORM, but for some reason it keeps throwing me this error.我试图使用 GORM 创建一个用户表,但由于某种原因,它一直向我抛出这个错误。

2022/08/29 01:31:58 /app/infra/database/db.go:26 Error 1075: Incorrect table definition; there can be only one auto column and it must be defined as a key

[0.156ms] [rows:0] ALTER TABLE `users` ADD `id` bigint unsigned AUTO_INCREMENT

I tried not using gorm.Model , and still throws me an error.我尝试不使用gorm.Model ,但仍然给我一个错误。 This is my user model:这是我的用户 model:

type User struct {
    gorm.Model
    Name string
}

And here is my initialization:这是我的初始化:

dsn := fmt.Sprintf("%s:%s@(%s:3306)/%s?charset=utf8&parseTime=True",
        os.Getenv("DB_USERNAME"),
        os.Getenv("DB_PASSWORD"),
        os.Getenv("DB_URL"),
        os.Getenv("DB_NAME"),
    )

    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
    if err != nil {
        log.Print(err)
        panic("error connecting to the database")
    }

    db.AutoMigrate(&user.User{})
    return db, nil

Pretty sure I'm doing this correctly, but if you see something strange please let me know, I'm just learning on how to use this ORM很确定我这样做是正确的,但如果你看到一些奇怪的东西请告诉我,我只是在学习如何使用这个 ORM

Deleting the old table will remove the error.删除旧表将消除错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM