dongmi1941 2018-07-19 22:07
浏览 59
已采纳

模型没有主键

I'm using https://github.com/go-pg/pg for my PostegreSQL database and Go. I'm trying to get the value of a table Settings that has the column site_name but for some reason it is giving me the error panic: model=Settings does not have primary keys

package mypackage

import (
    "database"
)

type Settings struct {
    SiteName string
}

func Get() string {
    var name Settings

    err := Db.Model(&name).First()
    if err != nil {
        panic(err)
    }

    return name.SiteName
}

I don't have the experience to really understand what's going on here or how to fix it. Any solutions? Thanks!

Example (FirstRow): https://godoc.org/github.com/go-pg/pg#DB.Select

  • 写回答

1条回答 默认 最新

  • douyun1852 2018-07-19 23:43
    关注

    The ORM requires you to define pks, so you will have to add it to the struct as well as your db table.

    https://github.com/go-pg/pg/blob/master/orm/query.go#L558 https://github.com/go-pg/pg/blob/d4fc7afde3ee9d0a780f9c67daf8a8a3bfd84060/orm/table.go#L124

    So add an Id field to your struct

    type Settings struct {
        Id       int64
        SiteName string
    }
    

    If you want to use an ORM you have to play by it's rules :) If you want more control try using sqlx instead

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计