登录
首页 >  Golang >  Go问答

查询第一条记录时不指定主键

来源:stackoverflow

时间:2024-02-22 19:36:24 428浏览 收藏

golang学习网今天将给大家带来《查询第一条记录时不指定主键》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

问题内容

我正在编写一些示例代码来理解 gorm,但似乎在设置 primary_key 值时遇到问题。结果,生成的 sql 查询被破坏。

请看示例代码: 包主要

import (
        "os"
        "fmt"
        "time"
        "gorm.io/driver/postgres"
        "gorm.io/gorm"
)

type post struct {
        id              int             `json:"id" gorm:"primary_key:id"`
        url             string          `gorm:"url"`
        content         string          `gorm:"content"`
        created_at      time.time       `gorm:"created_at"`
        normalized      string          `gorm:"normalized"`
        account_id      int             `gorm:"account_id"`
        posthash        []byte          `gorm:"posthash"`
        received_at     time.time       `gorm:"received_at"`
}

func main() {
        dsn := "user=postgres dbname=localtest"
        db, err := gorm.open(postgres.open(dsn), &gorm.config{})
        if err != nil {
                fmt.println("an error occurred", err)
                os.exit(1)
        }

        db.automigrate(&post{})
        var post post
        db.first(&post, 1)
        fmt.println(post)
}

当我运行此代码时,我收到以下错误:

$ go run gorm_test.go

2020/12/01 00:34:06 /home/farhan/gorm_test.go:32 ERROR: syntax error at or near "=" (SQLSTATE 42601)
[0.128ms] [rows:0] SELECT * FROM "posts" WHERE "posts". = 1 ORDER BY "posts". LIMIT 1
{0   {0 0 }  0 [] {0 0 }}

此错误的性质表明 primary_key 值未设置。我尝试了 primarykeyprimarykey,但似乎都不起作用。有什么想法吗?


解决方案


❗️使用导出 id 字段

在 go 中,当字段名称以小写字母开头时,表示该字段是私有的(在 go 中称为“未导出”)。 gorm 作为第三方包,无法查看您的结构内部,无法知道是否有 id 字段或任何其他未导出的字段。

解决方案是确保导出需要来自数据库的所有字段:

type Post struct {
  ID uint `json:"id" gorm:"primaryKey"`
  ...
}

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>