Handler特性允许您轻松地复用常见的逻辑。

示例1,查询

  1. func AmountGreaterThan1000(m *gdb.Model) *gdb.Model {
  2. return m.WhereGT("amount", 1000)
  3. }
  4. func PaidWithCreditCard(m *gdb.Model) *gdb.Model {
  5. return m.Where("pay_mode_sign", "credit_card")
  6. }
  7. func PaidWithCod(m *gdb.Model) *gdb.Model {
  8. return m.Where("pay_mode_sign", "cod")
  9. }
  10. func OrderStatus(statuses []string) func(m *gdb.Model) *gdb.Model {
  11. return func(m *gdb.Model) *gdb.Model {
  12. return m.Where("status", statuses)
  13. }
  14. }
  15. var (
  16. m = g.Model("product_order")
  17. )
  18. m.Handler(AmountGreaterThan1000, PaidWithCreditCard).Scan(&orders)
  19. // SELECT * FROM `product_order` WHERE `amount`>1000 AND `pay_mode_sign`='credit_card'
  20. // 查找所有金额大于 1000 的信用卡订单
  21. m.Handler(AmountGreaterThan1000, PaidWithCod).Scan(&orders)
  22. // SELECT * FROM `product_order` WHERE `amount`>1000 AND `pay_mode_sign`='cod'
  23. // 查找所有金额大于 1000 的 COD 订单
  24. m.Handler(AmountGreaterThan1000, OrderStatus([]string{"paid", "shipped"})).Scan(&orders)
  25. // SELECT * FROM `product_order` WHERE `amount`>1000 AND `status` IN('paid','shipped')
  26. // 查找所有金额大于1000 的已付款或已发货订单

示例2,分页

  1. func Paginate(r *ghttp.Request) func(m *gdb.Model) *gdb.Model {
  2. return func(m *gdb.Model) *gdb.Model {
  3. type Pagination struct {
  4. Page int
  5. Size int
  6. }
  7. var pagination Pagination
  8. _ = r.Parse(&pagination)
  9. switch {
  10. case pagination.Size > 100:
  11. pagination.Size = 100
  12. case pagination.Size <= 0:
  13. pagination.Size = 10
  14. }
  15. return m.Page(pagination.Page, pagination.Size)
  16. }
  17. }
  18. m.Handler(Paginate(r)).Scan(&users)
  19. m.Handler(Paginate(r)).Scan(&articles)