Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Gorm not creating full table from struct, how to fix?

Gorm create only id field, and ignores others fields

Gorm: 1.25.7(latest)

package main

import (
    "gorm.io/driver/sqlite"
    "gorm.io/gorm"
)

type Word struct {
    ID           uint
    symbols      string
    symbolsCount int
}


func main() {

    db, err := gorm.Open(sqlite.Open("words.db"), &gorm.Config{})
    if err != nil {
        panic("failed to connect database")
    }

    db.AutoMigrate(&Word{})

    db.Create(&Word{
        symbols:      "test",
        symbolsCount: len("test"),
    })

}

Tryed default from docs, and expect do that was written.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It just create db, then create table words, and it contains only id.

>Solution :

Unexported struct fields (members starting with a lowercase letter) are not considered for any operation in GORM. The following updated code should yield the result you expected:

package main

import (
    "gorm.io/driver/sqlite"
    "gorm.io/gorm"
)

type Word struct {
    ID           uint
    Symbols      string // <- Note the uppercase!
    SymbolsCount int    // <- Note the uppercase!
}


func main() {

    db, err := gorm.Open(sqlite.Open("words.db"), &gorm.Config{})
    if err != nil {
        panic("failed to connect database")
    }

    db.AutoMigrate(&Word{})

    db.Create(&Word{
        Symbols:      "test",
        SymbolsCount: len("test"),
    })

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading