【发布时间】:2020-04-22 18:08:41
【问题描述】:
我正在使用 postgres 和 gorm。这是我的模型:
package models
import "github.com/jinzhu/gorm"
type User struct {
gorm.Model
Username string `gorm:"unique_index;not null"`
Hash string `gorm:"not null"`
IsAdmin bool `gorm:"not null"`
IsUser bool `gorm:"not null"`
IsActive bool `gorm:"not null"`
RegEmail bool `gorm:"not null"`
RegFb bool `gorm:"not null"`
RegGoogle bool `gorm:"not null"`
}
type NewsPaper struct {
gorm.Model
Name string `gorm:"not null"`
NamBN string `gorm:"not null"`
LogoUrl string `gorm:"not null"`
Slug string `gorm:"unique_index;not null"`
IsActive bool `gorm:"not null"`
IsWeb bool `gorm:"not null"`
IsMobile bool `gorm:"not null"`
}
和 db 函数:
package bootstrap
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
"github.com/u/projName/models"
)
var db *gorm.DB
// initialize database
func Init() {
var adapter string
adapter = App.DBConfig.String("adapter")
switch adapter {
case "postgres":
postgresConn()
break
default:
panic("Undefined connection on config.local.yaml")
}
}
func postgresConn() {
var (
connectionString string
err error
)
connectionString = fmt.Sprintf("connection info")
if db, err = gorm.Open("postgres", connectionString); err != nil {
panic(err)
}
if err = db.DB().Ping(); err != nil {
panic(err)
}
db.LogMode(true)
}
//Gorm: return GORM's postgres database connection instance.
func DBManager() *gorm.DB {
var adapter string
adapter = App.DBConfig.String("adapter")
switch adapter {
case "postgres":
postgresConn()
break
default:
panic("Undefined connection on config.yaml")
}
err := db.AutoMigrate(&models.NewsPaper{}, &models.User{}).Error
if err != nil {
panic(err)
}
return db
}
当我运行主函数时,它不会引发任何错误。我检查了数据库没有表。
【问题讨论】:
-
尝试调试
db.AutoMigrate()调用。