添加商店功能
This commit is contained in:
56
controllers/goods/getgoods.go
Normal file
56
controllers/goods/getgoods.go
Normal file
@@ -0,0 +1,56 @@
|
||||
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,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user