【发布时间】:2018-07-23 05:20:04
【问题描述】:
我在这里和谷歌上都浏览过相关问题。
我正在使用带有 SQLite3 的 Gorm。
每当我尝试在我的结构上运行任一函数时,都会出现错误。当我调试并单步执行时,我看到表名是“”。 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"``
}
我的常见迁移函数是:
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 ]
仅供参考,不赞成投票 - 这是一个合理的问题,因为我在文档摘要页面上采用了 gorm 示例,基本上只是更改了结构。并且该结构正在使用正确的基本类型(除了将其重新放入原始帖子中的代码的切片)并且该错误不是很有帮助。我看到在空白表名错误之前有一个语法错误 - 但为什么?我给 GORM 一个有效的结构吗?
【问题讨论】:
-
错误是不言自明的:您不能将切片用作 sqlite3 的类型。您还有什么问题?
-
你是对的。我确实已经从结构和 NewUser() 函数中删除了它。没有意识到它又回来了。但错误仍然存在 - 空白表名。