Search code examples
gogo-gorm

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.

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