查询使用GORM选择列

huangapple go评论85阅读模式
英文:

Query select columns with GORM

问题

func GetShopCategory(c *fiber.Ctx) error {
    var shopCategories []model.ShopCategory
    err := model.DB.Select("ID", "Name", "Slug").Find(&shopCategories)
    if err.Error != nil {
        return c.SendStatus(fiber.StatusNoContent)
    }
    return c.JSON(shopCategories)
}

我有一个 shop_category 表。我想只显示选定列(如 "ID"、"Name"、"Slug")的所有表格。那么我该如何响应只包含这些列的表格数据?我不想显示其他列的名称。

英文:
func GetShopCategory(c *fiber.Ctx) error {
	var shopCategories []model.ShopCategory
	err := model.DB.Select("ID","Name","Slug").Find(&shopCategories)
	if err.Error != nil {
		return c.SendStatus(fiber.StatusNoContent)
	}
	return c.JSON(shopCategories)
}

I have a shop_category table. I want to show all table with selected columns like "ID","Name","Slug" only. so how can I response table's data with only these column. i don't wanna show other columns name.

答案1

得分: 1

你可以使用“Smart Select Fields”来实现这个功能。

type APIShopCategory struct {
    ID uint
    Name string
    Slug string
}


func GetShopCategory(c *fiber.Ctx) error {
    var shopCategories []APIShopCategory
    err := model.DB.Model(&model.ShopCategory{}).Find(&shopCategories)
    if err.Error != nil {
        return c.SendStatus(fiber.StatusNoContent)
    }
    return c.JSON(shopCategories)
}
英文:

You can accomplish that with 'Smart Select Fields'

type APIShopCategory struct {
    ID uint
    Name string
    Slug string
}


func GetShopCategory(c *fiber.Ctx) error {
    var shopCategories []APIShopCategory
    err := model.DB.Model(&model.ShopCategory{}).Find(&shopCategories)
    if err.Error != nil {
        return c.SendStatus(fiber.StatusNoContent)
    }
    return c.JSON(shopCategories)
}

huangapple
  • 本文由 发表于 2021年10月10日 17:10:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/69513820.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定