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 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?