Josh W
Josh W

Reputation: 29

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.

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.

Upvotes: 0

Views: 880

Answers (1)

M_x
M_x

Reputation: 878

  • Rewrite your code to this and always remember in Gorm we need to have Model Fields Capitalised
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)
}

Upvotes: 1

Related Questions