登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-20 09:54:16 187浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《Gorm 自动迁移创建一个没有用户定义属性的表 (postgresql)》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

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)
}

连接字符串是正确的,因为 db.automitrate(&b) 连接数据库并实现 id 和 gorm.model 属性(createdat 等),但它没有添加我的属性标题、作者和描述。 p>

我花了一整天的时间在谷歌上搜索,但在其他地方找不到这个错误。有人可以帮忙吗?另外,我在运行脚本之前删除了 postgres 中的 books 表。


正确答案


  • 将您的代码重写为此,并始终记住在 gorm 中我们需要将模型字段大写
855815536​​526

终于介绍完啦!小伙伴们,这篇关于《Gorm 自动迁移创建一个没有用户定义属性的表 (postgresql)》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>