英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论