You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GORM Find方法无法返回全部字段的问题排查

GORM查询仅返回id和name字段的原因分析

使用GORM的Find方法查询company表时,仅能获取id和name字段值,createdAt、updatedAt、newId字段值均为空,相关信息如下:

数据库表结构

CREATE TABLE `company` (
  `id` varchar(36) NOT NULL,
  `createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `name` varchar(255) NOT NULL,
  `newId` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Go实体定义(company.go)

package entities

import "time"

type Company struct {
    Id        string    `json:"id" gorm:"column:id;primaryKey"`
    CreatedAt time.Time `json:"createdAt" gorm:"column:createdAt"`
    UpdatedAt time.Time `json:"updatedAt" gorm:"column:updatedAt"`
    Name      string    `json:"name" gorm:"column:name"`
    NewId     string    `json:"newId" gorm:"column:newId"`
}

查询代码(companies.go控制器)

var companys []entities.Company
result := db.Find(&companys)
c.JSON(http.StatusOK, &result)

问题原因

  • 字段映射大小写不匹配:MySQL默认配置(如lower_case_table_names=1)会将表名和字段名自动转换为小写,因此建表语句中的createdAt、updatedAt、newId实际存储为createdat、updatedat、newid。但实体类的GORM标签使用了驼峰命名(如gorm:"column:createdAt"),大小写不匹配导致GORM无法将数据库字段值映射到结构体字段,最终这些字段值为空。
  • 错误返回GORM查询结果对象:代码中返回的是&result(GORM的DB实例,包含查询状态、错误等元数据),而非实际存储查询结果的companys切片。JSON序列化DB对象时,不会正确输出查询到的公司数据,导致前端看到的非id、name字段为空。

内容的提问来源于stack exchange,提问作者Fazeela MukhappillyAboobacker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 01:27:27