The Handler feature allows you to easily reuse common logic.

Example 1: Query

  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. // Find all credit card orders with an amount greater than 1000
  21. m.Handler(AmountGreaterThan1000, PaidWithCod).Scan(&orders)
  22. // SELECT * FROM `product_order` WHERE `amount`>1000 AND `pay_mode_sign`='cod'
  23. // Find all COD orders with an amount greater than 1000
  24. m.Handler(AmountGreaterThan1000, OrderStatus([]string{"paid", "shipped"})).Scan(&orders)
  25. // SELECT * FROM `product_order` WHERE `amount`>1000 AND `status` IN('paid','shipped')
  26. // Find all orders with an amount greater than 1000 that are paid or shipped

Example 2: Pagination

  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)