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:[email protected]: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
}
CodePudding user response:
two ways for answer after check many ways
first of i must use Find insted of First another hand i try retrieve data by thse two ways
1:
err := m.db.Debug().Table("CompanyNames").Find(cn, "Id = ?", id).Error
2:
err := m.db.Debug().Table("CompanyNames").Find(cn, map[string]interface{}{
"Id": Id,
}).Error
as reserach the beter way is the second way
CodePudding user response:
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"`
}