在go-gorm中,”mssql: Invalid column name ‘id'”的意思是”mssql: 无效的列名’id'”。

huangapple go评论78阅读模式
英文:

In go - gorm "mssql: Invalid column name 'id'

问题

这是我的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"`
}

这是从数据库检索数据的repo:

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
}

在 "http" 上,我使用 echo 框架编写了以下代码:

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

	logic = lg
}

当我调用 ReadAll 函数时,记录完全检索到数据,这意味着我已经正确连接到数据库。但是,当我尝试通过 "id" 获取数据时,出现了错误:

mssql: Invalid column name 'id'.

我的错误在哪里?

另一方面,如果我将结构体中的 Id 字段注释掉,像这样:

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"`
}

我会得到新的错误:

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

更新:

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
}
英文:

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

}

答案1

得分: 3

在阅读了你的回答后,我找到了你的问题。正如上面的评论所说,如果你展示出你的表结构,那么找到问题会更容易。

你查询中指定的列名是 Id,而你的结构没有明确指定这个名称。根据 Gorm 约定,你的 Id 字段会被转换为 id。这个问题可以通过添加 标签 来解决。

例如:

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"`
}
英文:

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"`
}

答案2

得分: 1

检查了很多种方法后,有两种回答的方式。

首先,我必须使用Find而不是First,另一方面,我尝试通过这两种方式检索数据。

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

更新:
正如@kocoler所写,我进行了测试,结果是正确的,而且我认为对于性能来说,First比Find更好。
strong text
根据研究,第二种方式更好。

英文:

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

Update :
As @kocoler wrote, I tested and it was currect, also I think First is beter for performance VS Find
strong text
as reserach the beter way is the second way

huangapple
  • 本文由 发表于 2022年8月2日 20:56:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/73207946.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定