Files
toutoukan/controllers/goods/getgoods.go
2025-09-24 20:57:04 +08:00

57 lines
1.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package goods
import (
"net/http"
"time"
"toutoukan/init/databaseInit"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
// GoodsList 数据库商品列表结构体用于GORM查询
type GoodsList struct {
ID int64 `gorm:"column:id;primaryKey;autoIncrement" json:"id"`
Name string `gorm:"column:name" json:"name"`
Description string `gorm:"column:description" json:"description"`
Points int `gorm:"column:points" json:"points"`
Stock int `gorm:"column:stock" json:"stock"`
ImageURL string `gorm:"column:image_url" json:"image_url"`
Status int8 `gorm:"column:status" json:"status"`
CreatedAt time.Time `gorm:"column:created_at" json:"created_at"`
UpdatedAt time.Time `gorm:"column:updated_at" json:"updated_at"`
}
// TableName 为 GoodsList 结构体指定数据库表名
func (GoodsList) TableName() string {
return "goods_list"
}
func GetGoods(c *gin.Context) {
var goods []GoodsList
// 查询 status = 1 (上架) 且 stock > 0 的所有商品
if err := databaseInit.UserDB.Table("goods_list").
Where("status = ? AND stock > ?", 1, 0).
Find(&goods).Error; err != nil {
if err == gorm.ErrRecordNotFound {
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "暂无上架商品",
"data": []GoodsList{},
})
} else {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "查询商品列表失败: " + err.Error(),
})
}
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "获取商品列表成功",
"data": goods,
})
}