使用 RAW 内置函数 GORM 时出现未声明的名称 const。

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

Undeclared Name const when using RAW Built-in function GORM

问题

我想在我的个人项目中使用GORM中的Raw函数作为要求。

这是我的实体:

  1. type Student struct {
  2. ID int `json:"id"`
  3. Name string `json:"name"`
  4. Address string `json:"address"`
  5. }

所以我创建了一个常量来在RAW参数中调用:

  1. const RetrieveData = `SELECT id, name, address FROM users WHERE id = ?`

然后我构建了一个函数:

  1. type mysqlRepository struct {
  2. GormDb *gorm.DB
  3. }
  4. func (repo *mysqlRepository) RetrieveUserData(id int) (Student, error) {
  5. data := Student{}
  6. db := db.GormDb.Raw(RetrieveData, 3).Scan(&data)
  7. return data, db.Error
  8. }

为什么我的函数会出现警告:

  1. undeclared name: RetrieveData (compile)go-staticcheck

这是因为未声明的名称:RetrieveData 是一个未声明的变量。

英文:

I want to use Raw function in GORM as requirements on my personal project

This is my entity

  1. type Student struct {
  2. ID int `json:"id"`
  3. Name string `json:"name"`
  4. Address string `json:"address"`
  5. }

so I create constant to be called in RAW param

  1. const (RetrieveData = `SELECT id, name, address FROM users WHERE id = ?`)

And then I build function

  1. type mysqlRepository struct {
  2. GormDb *gorm.DB
  3. }
  4. func(repo *mysqlRepository) RetrieveUserData(id int) (Student, error) {
  5. data := Student{}
  6. db := db.GormDb.Raw(RetrieveData, 3).Scan(&data)
  7. return data, db.Error
  8. }

Why do I get warning on my function

  1. undeclared name: RetrieveData (compile)go-staticcheck

Is it because untype string type?

答案1

得分: 1

很可能RetrieveDatafunc RetrieveUserData中不可访问。
要么将其移动到相同的包中,要么使用<package_name>.RetrieveData

英文:

Most probably RetrieveData is not accessible in func RetrieveUserData
Either move it to same package or use &lt;package_name&gt;.RetrieveData

答案2

得分: 0

使用方法find()

  1. err := DB.Raw("[sql]").Find(&data).Error
英文:

use method find()

  1. err := DB.Raw(&quot;[sql]&quot;).Find(&amp;data).Error

huangapple
  • 本文由 发表于 2022年8月24日 17:50:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/73470995.html
匿名

发表评论

匿名网友

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

确定