我想queryOne使用go-pg它只返回一行到一个对象而不是数组。这是我的简单代码:var reportMessage *ReportMessage _, err := db.Model((*ReportMessage)(nil)).QueryOne(&reportMessage, ` SELECT SUM(total_order) total_order, SUM(total_message) total_message, SUM(hsm_message) hsm_message , SUM(outbound_message) outbound_message , SUM(inbound_message) inbound_message , SUM(total_order_amount) total_order_amount FROM report_message rm WHERE seller_id =? and "date" between ? and ?; `, sellerID, dateStart, dateEnd) if err != nil { return nil, err } return reportMessage, niltype ReportMessage struct { ID string `json:"id"` SellerID string `json:"seller_id"` TotalOrder int `json:"total_order"` Date time.Time `json:"date"` HsmMessage int `json:"hsm_message"` TotalMessage int `json:"total_message"` OutboundMessage int `json:"outbound_message"` InboundMessage int `json:"inbound_message"` TotalOrderAmount float32 `json:"total_order_amount"`}我希望它只返回reportMessage 而不是一个数组。这是我的错误:json: cannot unmarshal number into Go value of type models.ReportMessage如何只查询一行并将其返回给对象而不是数组?
1 回答
千巷猫影
TA贡献1829条经验 获得超7个赞
您需要初始化模型的一个实例并传递一个指向该实例的指针,而不是传递一个指向模型未初始化的 nil 指针的指针。
reportMessage := new(ReportMessage)
_, err := db.Model((*ReportMessage)(nil)).QueryOne(reportMessage, `
SELECT
SUM(total_order) total_order,
SUM(total_message) total_message,
SUM(hsm_message) hsm_message ,
SUM(outbound_message) outbound_message ,
SUM(inbound_message) inbound_message ,
SUM(total_order_amount) total_order_amount
FROM report_message rm WHERE seller_id =? and "date" between ? and ?;
`, sellerID, dateStart, dateEnd)
if err != nil {
return nil, err
}
return reportMessage, nil
- 1 回答
- 0 关注
- 107 浏览
添加回答
举报
0/150
提交
取消