【问题标题】:gorm failed to create tables without any errorsgorm 未能创建没有任何错误的表
【发布时间】: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()调用。

标签: go go-gorm


【解决方案1】:

你必须在你的模型中调用 gorm migrate 函数。

db.AutoMigrate(&User{},&NewsPaper{})

它将为您的模型创建表。

【讨论】:

    猜你喜欢
    • 2017-02-12
    • 2015-03-21
    • 2014-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    • 2020-04-24
    • 2015-07-07
    相关资源
    最近更新 更多