简体   繁体   English

Gorm 自动迁移创建没有用户定义属性的表(postgresql)

[英]Gorm auto-migration creating a table with no user-defined attributes (postgresql)

package main

import (
    "fmt"

    _ "github.com/jinzhu/gorm/dialects/postgres"
    "gorm.io/driver/postgres"
    "gorm.io/gorm"
)

type Books struct {
    gorm.Model
    ID              uint
    title           string
    author          string
    description     string
    display_picture byte
}


func main() {
    
    dsn := //successful create connection string
    
    db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})

    if err != nil {
        // fmt.Println(err)
        panic(err)
    }
    b := Books{}
    db.AutoMigrate(&b)
    data := Books{
        title:       "Invisible Cities",
        author:      "Italio Calvino",
        description: "This book shows you the power of prose. It's a beautiful read which will make you feel like you're floating on a cloud.",
    }
    db.Create(&data)
    fmt.Println(data)
}

The connection string is correct because the db.AutoMitrate(&b) connects with the database and implements the ID and the gorm.Model attributes (createdAt etc) however it doesn't add my attributes title, author and description.连接字符串是正确的,因为 db.AutoMitrate(&b) 与数据库连接并实现了 ID 和 gorm.Model 属性(createdAt 等),但是它没有添加我的属性标题、作者和描述。

I've spend the whole day googling but I cant find this error anywhere else.我花了一整天的时间在谷歌上搜索,但在其他任何地方都找不到这个错误。 Can anyone help?任何人都可以帮忙吗? Also I am deleting my Books table in postgres before running the script.在运行脚本之前,我还在 postgres 中删除了我的 Books 表。

  • Rewrite your code to this and always remember in Gorm we need to have Model Fields Capitalised将您的代码重写为此并始终记住在 Gorm 中我们需要将 Model 字段大写
package main

import (
    "fmt"

    _ "github.com/jinzhu/gorm/dialects/postgres"
    "gorm.io/driver/postgres"
    "gorm.io/gorm"
)

type Books struct {
    gorm.Model
    ID              uint
    Title           string
    Author          string
    Description     string
    Display_Picture byte
}


func main() {
    
    dsn := //successful create connection string
    
    db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})

    if err != nil {
        // fmt.Println(err)
        panic(err)
    }
    b := Books{}
    db.AutoMigrate(&b)
    data := Books{
        title:       "Invisible Cities",
        author:      "Italio Calvino",
        description: "This book shows you the power of prose. It's a beautiful read which will make you feel like you're floating on a cloud.",
    }
    db.Create(&data)
    fmt.Println(data)
}

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

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