feat(repo): 添加产品和分类的数据库查询功能

- 新增获取单个产品的 SQL 查询语句
- 新增获取所有产品的 SQL 查询语句
- 新增获取所有分类的 SQL 查询语句- 实现产品和分类数据的扫描解析逻辑
- 在 SqlRepository 中添加对应的数据访问方法- 支持通过 ID 查询特定产品信息
- 支持联表查询产品及其所属分类信息
This commit is contained in:
2025-11-08 17:56:58 +08:00
parent 6923c9be6c
commit 2943d0f839
5 changed files with 96 additions and 0 deletions

View File

@@ -0,0 +1,46 @@
package repo
import "sportstore/models"
func (repo *SqlRepository) GetProduct(id int) (p models.Product) {
row := repo.Commands.GetProduct.QueryRowContext(repo.Context, id)
if row.Err() == nil {
var err error
if p, err = scanProduct(row); err != nil {
repo.Logger.Panicf("Cannot scan data product: %v ", err.Error())
}
} else {
repo.Logger.Panicf("Cannot exec GetProduct command: %v ", row.Err().Error())
}
return
}
func (repo *SqlRepository) GetProducts() (results []models.Product) {
rows, err := repo.Commands.GetProducts.QueryContext(repo.Context)
if err == nil {
if results, err = scanProducts(rows); err != nil {
repo.Logger.Panicf("Cannot scan data products: %v ", err.Error())
return
}
} else {
repo.Logger.Panicf("Cannot exec GetProducts command: %v ", err.Error())
}
return
}
func (repo *SqlRepository) GetCategories() []models.Category {
results := make([]models.Category, 0, 10)
rows, err := repo.Commands.GetCategories.QueryContext(repo.Context)
if err == nil {
for rows.Next() {
c := models.Category{}
if err := rows.Scan(&c.ID, &c.CategoryName); err != nil {
repo.Logger.Panicf("Cannot scan data category: %v ", err.Error())
}
results = append(results, c)
}
} else {
repo.Logger.Panicf("Cannot exec GetCategories command: %v ", err.Error())
}
return results
}

View File

@@ -0,0 +1,27 @@
package repo
import (
"database/sql"
"sportstore/models"
)
func scanProducts(rows *sql.Rows) (products []models.Product, err error) {
products = make([]models.Product, 0, 10)
for rows.Next() {
p := models.Product{Category: &models.Category{}}
if err = rows.Scan(&p.ID, &p.Name, &p.Description, &p.Price,
&p.Category.ID, &p.Category.CategoryName); err == nil {
products = append(products, p)
} else {
return
}
}
return
}
func scanProduct(row *sql.Row) (p models.Product, err error) {
p = models.Product{Category: &models.Category{}}
err = row.Scan(&p.ID, &p.Name, &p.Description, &p.Price,
&p.Category.ID, &p.Category.CategoryName)
return p, err
}

View File

@@ -0,0 +1,3 @@
SELECT Categories.Id, Categories.Name
FROM Categories
ORDER BY Categories.Id

View File

@@ -0,0 +1,10 @@
SELECT Products.Id,
Products.Name,
Products.Description,
Products.Price AS ProductPrice,
Categories.Id AS CategoryId,
Categories.Name AS CategoryName
FROM Products,
Categories
WHERE Products.Category = Categories.Id
AND Products.Id = ?

View File

@@ -0,0 +1,10 @@
SELECT Products.Id,
Products.Name,
Products.Description,
Products.Price AS ProductPrice,
Categories.Id AS CategoryId,
Categories.Name AS CategoryName
FROM Products,
Categories
WHERE Products.Category = Categories.Id
ORDER BY Products.Id