Skip to content
Advertisement

In go – gorm “mssql: Invalid column name ‘id’

This is my model in go

package models

import (
"time"

"gorm.io/gorm"
 )

type VID uint

type CompanyNames struct {
Id   VID    `json:"id,omitempty"`
Name string `json:"name,omitempty"`
CreateDate time.Time `json:"CreateDate,omitempty"`
ModifyDate time.Time `json:"ModifyDate,omitempty"`

}

and this is my repo(that retrieve data from database):

func (m *Repo) Read(id models.VID) (*models.CompanyNames, error) {
var (
    cn = &models.CompanyNames{}
)
err := m.db.Debug().Table("CompanyNames").First(cn, &id).Error

if err != nil {
    return nil, err
}
return cn, err

}

On “http” I write this code with echo

func NewHttp(e *echo.Group, lg *Logic) {
g := e.Group("/companyname")
g.GET("", readAll)
g.GET("/:Id", read)

logic = lg
}

When I cal my ReadAll record rerieve data completly , it’s mean I conected to database currectly,But whene I try get data by “id” got an error that :

mssql: Invalid column name ‘id’.

Whet is my mistake another hand make id in my struct as a comment like this:>

type CompanyNames struct {
//Id   VID    `json:"id,omitempty"`
Name string `json:"name,omitempty"`
CreateDate time.Time `json:"CreateDate,omitempty"`
ModifyDate time.Time `json:"ModifyDate,omitempty"`
}

got new error that

mssql: Invalid column name ‘name’. [2690.814ms] [rows:0] SELECT * FROM “CompanyNames” WHERE “CompanyNames”.”name” = ‘1’ ORDER BY “CompanyNames”.”id” OFFSET 0 ROW FETCH NEXT 1 ROWS ONLY

Update:

func Cunnection() (*gorm.DB, error) { var ( err error db *gorm.DB ) dsn := “sqlserver://DbUser:mypass@111.111.111.111:1433?database=myDb”

db, err = gorm.Open(sqlserver.Open(dsn), &gorm.Config{})

if err != nil {
    return nil, err
}
// err = db.Debug().AutoMigrate(&models.CompanyNameModel{})
// if err != nil {
//  return nil, err
// }
return db, nil

}

Advertisement

Answer

After reading your own answer, I found your question. As the comments above say, it’s easier to find the problem if you show your table structure.

The column name specified by your query is Id and your structure does not explicitly specify this name. According to the Grom convention, your Id field will be converted into id. This problem can be solved by adding tags.

For example:

package models

import (
    "time"

    "gorm.io/gorm"
)

type VID uint

type CompanyNames struct {
    Id   VID    `json:"id,omitempty" gorm:"column:Id"`
    Name string `json:"name,omitempty" gorm:"column:Name"`
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement