【发布时间】:2021-06-14 02:17:47
【问题描述】:
我正在尝试通过基于项目的学习来学习 Golang。我摆在自己面前的问题是模拟客户将产品添加到他们的购物车中。目前,我有 Cart.go 这样的模型..
type Cart struct {
ID string
Customer Customer
CustomerID string
Product Product
ProductID string
CreatedAt time.Time
UpdatedAt time.Time
}
在购物车模型上,我有一个函数定义为
func (c *Cart) GetAllItemsInCart(db *gorm.DB, customer_id string) (*gorm.DB, error) {
items := db.Raw("SELECT id, product_id FROM carts WHERE customer_id = ?", customer_id).Scan(&c)
return items, nil
}
这个函数在控制器中调用
func (server *Server) GetAllCartItems(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
cart := models.Cart{}
items, err := cart.GetAllItemsInCart(server.DB, id)
if err != nil {
responses.ERROR(w, http.StatusInternalServerError, err)
return
}
responses.JSON(w, http.StatusOK, items)
}
据我所知,目前Scan() 将扫描结构的值,或者在这种情况下将找到的数据加载到指定的结构中。但是,我看到的回复是
{
"Value": null,
"Error": null,
"RowsAffected": 2
}
这给了我 50% 的希望,因为 "RowsAffected": 2 是正确的。但是,有效载荷响应显然不是我想要的。任何指导将不胜感激,谢谢。
【问题讨论】:
-
使用
Scan(c),c已经是一个指针了。