cart_dal.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package dal
  2. import (
  3. "errors"
  4. "fmt"
  5. "xiaoniaokuaiyan.com/xiaoniao/entity"
  6. "xiaoniaokuaiyan.com/xiaoniao/util"
  7. )
  8. type Cart struct{}
  9. func (c *Cart) Get(customId int) ([]entity.ProductDB, error) {
  10. db := util.GetSqlDB()
  11. strSql := "select t1.quantity, t2.* from t_cart t1 left join t_product t2 on t1.pid = t2.id where cid = ?"
  12. plist := []entity.ProductDB{}
  13. err := db.Select(&plist, strSql, customId)
  14. if err != nil {
  15. return nil, err
  16. }
  17. return plist, nil
  18. }
  19. func (c *Cart) Update(customId, productId, quantity int, isAdd bool) (bool, error) {
  20. var strSql string = "select quantity from t_cart where cid = ? and pid =?"
  21. db := util.GetWriteSqlDB()
  22. var (
  23. quan int
  24. err error
  25. )
  26. db.Get(&quan, strSql, customId, productId)
  27. if quan <= 0 {
  28. if quantity < 1 {
  29. return false, errors.New("wrong param quantity")
  30. }
  31. strSql = "insert into t_cart(cid, pid, quantity) values(?,?,?);"
  32. _, err = db.Exec(strSql, customId, productId, quantity)
  33. } else {
  34. if isAdd {
  35. quantity = quan + quantity
  36. }
  37. if quantity < 1 {
  38. return false, errors.New("wrong param quantity")
  39. }
  40. strSql = "update t_cart set quantity = ? where cid = ? and pid = ?"
  41. _, err = db.Exec(strSql, quantity, customId, productId)
  42. }
  43. if err != nil {
  44. return false, err
  45. }
  46. return true, nil
  47. }
  48. func (c *Cart) Del(customId int, productIds []int) (bool, error) {
  49. if len(productIds) == 0 {
  50. return false, errors.New("wrong product id param")
  51. }
  52. var strSql = fmt.Sprintf("delete from t_cart where cid = %d and pid in(", customId)
  53. for _, pid := range productIds {
  54. strSql += fmt.Sprintf("%d,", pid)
  55. }
  56. strSql = strSql[0:len(strSql)-1] + ");"
  57. db := util.GetWriteSqlDB()
  58. _, err := db.Exec(strSql)
  59. if err != nil {
  60. return false, err
  61. }
  62. return true, nil
  63. }
  64. func (c *Cart) Clear(customId int) (bool, error) {
  65. strSql := "delete from t_cart where cid = ?"
  66. db := util.GetWriteSqlDB()
  67. _, err := db.Exec(strSql, customId)
  68. if err != nil {
  69. return false, err
  70. }
  71. return true, nil
  72. }
  73. var DefaultCartDal = &Cart{}