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

連接字符串是正確的,因為 db.AutoMitrate(&b) 與數據庫連接並實現了 ID 和 gorm.Model 屬性(createdAt 等),但是它沒有添加我的屬性標題、作者和描述。

我花了一整天的時間在谷歌上搜索,但在其他任何地方都找不到這個錯誤。 任何人都可以幫忙嗎? 在運行腳本之前,我還在 postgres 中刪除了我的 Books 表。

  • 將您的代碼重寫為此並始終記住在 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