先看一下表结构
type Products struct {
// 商品ID
ProductId int64 `json:"productId" form:"productId" gorm:"primaryKey;column:product_id" `
// 分类ID
CategoryId int64 `json:"categoryId" form:"categoryId" gorm:"column:category_id" `
// 商品名称
ProductName string `json:"productName" form:"productName" gorm:"column:product_name" `
// 商品描述
Description string `json:"description" form:"description" gorm:"column:description" `
// 价格
Price float32 `json:"price" form:"price" gorm:"column:price" `
// 库存数量
StockQuantity int64 `json:"stockQuantity" form:"stockQuantity" gorm:"column:stock_quantity" `
// 图片链接
ImageUrl string `json:"imageUrl" form:"imageUrl" gorm:"column:image_url" `
// 创建时间
CreatedTime time.Time `json:"createdTime" form:"createdTime" gorm:"autoCreateTime;column:created_time" `
// 更新时间
UpdatedTime time.Time `json:"updatedTime" form:"updatedTime" gorm:"autoUpdateTime;column:updated_time" `
}
然后主表,通过一个秒杀id查询 商品列表
type SeckillProducts struct {
// id
SeckillProductsId int64 `json:"seckillProductsId" form:"seckillProductsId" gorm:"primaryKey" `
// 秒杀表id
SeckillId int64 `json:"seckillId" form:"seckillId" `
// 商品id
ProductsId int64 `json:"productsId" form:"products_Id" `
// 库存数量
StockQuantity int64 `json:"stockQuantity" form:"stockQuantity" `
// 一对一关联商品
Products products.Products
}
使用gorm 查询
func GetProductListBySeckillId(seckillId string, page, size int) (utils.PageDto, error) {
var seckillProducts []SeckillProducts
var seckillProduct SeckillProducts
offset := (page - 1) * size // 计算偏移量
var total int64
utils.DB.Table("shop_seckill_products").
Select("shop_products.*, shop_seckill_products.*").
Joins("left join shop_products on shop_products.product_id = shop_seckill_products.products_id").
Where("shop_seckill_products.seckill_id = ?", seckillId).Count(&total)
var err error
// 执行关联查询
err = utils.DB.Preload("Products").Take(&seckillProduct).
Where("shop_seckill_products.seckill_id = ?", seckillId).
Offset(offset).Limit(size).
Find(&seckillProducts).Error
return utils.PageDto{
Current: page,
Size: size,
Records: seckillProducts,
Total: total,
}, err
}
标签:分页,form,一对一,id,column,json,products,gorm
From: https://www.cnblogs.com/MnysLjj/p/17801917.html