Query select columns with GORM

Viewed 279
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 Answers

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)
}
Related