首页 文章

Gorm AutoMigrate()和CreateTable()不起作用

提问于
浏览
1

我已经在谷歌这里和所有相关的问题 .

我正在使用Gorm和SQLite3 .

每当我尝试在我的struct上运行任一函数时,我都会收到错误 . 当我调试并单步执行时,我看到表名是“” . Gorm没有获得我的结构名称,即models.UserAuth . 如果我调用DropTable(models.UserAuth {})来显示没有名为user_auth的表(但至少它找出了表名) . 当我浏览数据库时,当然没有表格 .

我的结构是

type UserAuth struct {
    gorm.Model
    ProfileID int      `gorm:"not null" json:"profile_id"`
    Username  string   `gorm:"size:20;unique_index" json:"username"`
    Email     string   `gorm:"type:varchar(100);unique_index" json:"email"`
    Password  string   `gorm:"not null" json:"password"`
    Remember  bool     `gorm:"not null" json:"remeber"`
    TwoFA     bool     `gorm:"not null" json:"twofa"`
    Access    int      `gorm:"not null" json:"access"`
    State     int      `gorm:"not null" json:"state"`
    LastSeen  string   `gorm:"not null" json:"lastseen"``
}

我的COMMON迁移功能是:

func (d *Database) Migrate(m interface{}) {
    logEntry := fmt.Sprintf("Auto Migrating %s...", reflect.TypeOf(m))

    //d.db.DropTable(&models.UserAuth{})
    //d.db.CreateTable(&models.UserAuth{})

    // Do it the hard way
    //if d.db.HasTable(&m) == false {
    // Create table for model `User`
    //  d.db.CreateTable(&m)
    //  d.logThis.Info(fmt.Sprintf("%s %s with error %s", logEntry, "Failed", d.db.Error))
    //}

    // Migrate the schema
    db := d.db.AutoMigrate(&m) //<--- Line 84
    if db != nil && db.Error != nil {
        //We have an error
        d.logThis.Fatal(fmt.Sprintf("%s %s with error %s", logEntry, "Failed", db.Error))
    }
    d.logThis.Info(fmt.Sprintf("%s %s", logEntry, "Success"))
}

最后这是如何调用它:

app.Db.Migrate(models.UserAuth{})

调试的实际输出:

({PathToProject}/database/database.go:84) 
[2018-07-23 06:12:24]  near ")": syntax error 

({PathToProject}/database/database.go:84) 
[2018-07-23 06:12:24]  [0.99ms]  CREATE TABLE "" ( )  
[0 rows affected or returned ]

仅供参考,downvote是不必要的 - 这是一个合法的问题,因为我在文档摘要页面上采用了gorm示例,基本上只是改变了结构 . 并且结构使用了正确的基本类型(除了使其返回到原始帖子中的代码的切片之外)并且错误不是很有用 . 我看到空白表名称错误之前有一个SYNTAX错误 - 但为什么?我给GORM一个有效的结构吗?

1 回答

  • 1

    我很确定sqlite没有AuthIPs([]字符串的类型) . 我不确定GORM是否允许您编写自定义Valuer和Scanner接口方法,这些方法允许您将字符串转换为数组然后再返回,但这可能是您想要查看的内容 .

    更新:将 db := d.db.AutoMigrate(&m) 更改为 db := d.db.AutoMigrate(m) 以允许反射获取类型名称 .

    如果实现 tabler 接口,还可以更好地控制表的名称 .

    https://github.com/jinzhu/gorm/blob/master/scope.go#L305

    type tabler interface {
        TableName() string
    }
    

相关问题