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

使用GORM查询shop_category表如何仅返回ID、Name、Slug指定字段,不显示其他列

实现方案

你当前的代码已经通过Select方法指定了数据库查询时仅获取ID、Name、Slug三个字段,返回结果包含额外字段的核心原因是model.ShopCategory结构体的其他字段在JSON序列化时被默认输出,可通过以下两种方案解决:


方案1:修改原结构体JSON标签

在model.ShopCategory结构体不需要对外返回的字段上,加json:"-"标签,序列化时会自动忽略这些字段:

type ShopCategory struct {
    ID   uint   `json:"id"`
    Name string `json:"name"`
    Slug string `json:"slug"`
    // 以下字段JSON序列化时忽略
    CreatedAt time.Time `json:"-"`
    UpdatedAt time.Time `json:"-"`
    OtherField string `json:"-"`
}

调整后你现有的业务逻辑不需要做其他修改即可生效。


方案2:定义专属响应结构体(更推荐)

单独定义接口返回用的结构体,和数据库模型解耦,避免冗余字段暴露,同时也更符合分层设计规范,调整后的代码如下:

// 定义仅包含返回字段的响应结构体
type ShopCategoryResp struct {
    ID   uint   `json:"id"`
    Name string `json:"name"`
    Slug string `json:"slug"`
}

func GetShopCategory(c *fiber.Ctx) error {
    var shopCategories []ShopCategoryResp
    // 指定查询模型为ShopCategory,查询指定字段后直接映射到响应结构体
    err := model.DB.Model(&model.ShopCategory{}).Select("ID", "Name", "Slug").Find(&shopCategories).Error
    if err != nil {
        return c.SendStatus(fiber.StatusNoContent)
    }
    return c.JSON(shopCategories)
}

注意:你原代码中的错误处理写法有问题,Find方法返回的是*gorm.DB实例,需要直接取其Error字段进行判空。


内容的提问来源于stack exchange,提问作者Saifullah Shahen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 17:27:03