dongpao1905 2018-08-01 22:52
浏览 174
已采纳

如何查询GORM模型

I'm attempting to query a database given a model, and I'm getting a blank model as a response. I'm using Revel framework and GORM to create the model and query the database.

app.go

package controllers

import (
    "github.com/revel/revel"
    "route/to/models"
)

type App struct {
    *revel.Controller
    GormController
}

func (c App) Index() revel.Result {
    accounts := models.Account{}
    account := c.DB.Find(accounts)

    return c.RenderJSON(account)
}

gorm.go

package controllers

import (
    _ "github.com/jinzhu/gorm/dialects/postgres"
    "github.com/jinzhu/gorm"
    r "github.com/revel/revel"
)
type GormController struct {
    *r.Controller
    DB *gorm.DB
}

// it can be used for jobs
var Gdb *gorm.DB

// init db
func InitDB() {
    var err error
    // open db
    Gdb, err = gorm.Open("postgres", "host=hostname port=5432 user=postgres password=password dbname=some_db_name sslmode=disable")
    Gdb.LogMode(true) // Print SQL statements
    if err != nil {
        r.ERROR.Println("FATAL", err)
        panic(err)
    }
}

func (c *GormController) SetDB() r.Result {
    c.DB = Gdb
    return nil
}

Not sure where I'm going wrong, ultimately I want to do a select * from accounts;

Note: I can run a migration and create in the Index() function and the data is handled correctly.

  • 写回答

1条回答 默认 最新

  • dongzhuo1958 2018-08-01 23:18
    关注

    When populating a struct from the database, you need to pass a pointer for GORM to be able to populate it. Otherwise it's pass-by-value and GORM populates a copy and you never see it.

    And if you want to get all accounts you should pass a pointer to a slice of accounts. Regarding pointers versus values, a slice is different from a struct in that the underlying array can still be modified even in pass-by-value, but outside the function the slice length (and capacity) won't change even as the array is populated within the function, so it still won't behave as expected without a pointer.

    And you should check Error afterward:

    accounts := make([]models.Account, 0)
    if err := c.DB.Find(&accounts).Error; err != nil {
         if gorm.IsRecordNotFoundError(err) {
              // handle not found
         } else {
              // print/log/return error
         }
         return
    }
    
    // do something with accounts
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)