登录
首页 >  Golang >  Go问答

Gorm Find() 查询未填充保存结果集的模型中的所有字段

来源:stackoverflow

时间:2024-02-15 22:09:22 405浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《Gorm Find() 查询未填充保存结果集的模型中的所有字段》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

我遇到的问题是结果集中返回的tx没有设置所有字段。无法弄清楚为什么?它在实际的数据库表中具有价值。

// request object supplied in fetchtransactionwithhighestexpiry:
type provisionrequest struct {
        identity string     `json:"identity"`
        identitytype string `json:"identitytype"`
}

// struct to model database table
type transactions struct {
        identity string `gorm:"index;not null"`
        identitytype string 
}

// method where there is problem
func (c *dbclient) fetchtransactionwithhighestexpiry(req *model.provisionrequest) (model.transactions, error)  {
    var tx model.transactions
    res := c.client.model(&model.transactions{}).where("identity = ? and enddate  > ?", req.identity, time.now().unix()).order("enddate desc").first(&tx)
    return tx, res.error
}

我的交易只有身份集的值,而身份类型是一个空字符串。你知道我在这里做错了什么吗?

编辑 1:交易表架构

-- rp.transactions definition

CREATE TABLE `transactions` (
  `transaction_id` varchar(255) NOT NULL,
  `identity` varchar(255) DEFAULT NULL,
  `identityType` varchar(15) DEFAULT NULL,
  `serviceId` varchar(255) DEFAULT NULL,
  `partnerId` varchar(255) DEFAULT NULL,
  `countryId` varchar(255) DEFAULT NULL,
  `updatedAt` timestamp NULL DEFAULT NULL,
  `createdAt` timestamp NULL DEFAULT NULL,
  `startDate` int NOT NULL,
  `endDate` int NOT NULL,
  PRIMARY KEY (`transaction_id`),
  KEY `identity_idx` (`identity`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

正确答案


default,构建查询时,gorm 将使用 snake_case 约定将 identityidentitytype 字段转换为 identityidentity_type 列。

如果您的表格列的名称不同,则需要指定这一点。

// struct to model database table
type Transactions struct {
        Identity string `gorm:"index;not null"`
        IdentityType string `gorm:"column:identityType"`
}

本篇关于《Gorm Find() 查询未填充保存结果集的模型中的所有字段》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

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