Scopes 允许您轻松地复用常见的逻辑

查询

  1. func AmountGreaterThan1000(db *gorm.DB) *gorm.DB {
  2. return db.Where("amount > ?", 1000)
  3. }
  4. func PaidWithCreditCard(db *gorm.DB) *gorm.DB {
  5. return db.Where("pay_mode_sign = ?", "C")
  6. }
  7. func PaidWithCod(db *gorm.DB) *gorm.DB {
  8. return db.Where("pay_mode_sign = ?", "C")
  9. }
  10. func OrderStatus(status []string) func (db *gorm.DB) *gorm.DB {
  11. return func (db *gorm.DB) *gorm.DB {
  12. return db.Where("status IN (?)", status)
  13. }
  14. }
  15. db.Scopes(AmountGreaterThan1000, PaidWithCreditCard).Find(&orders)
  16. // 查找所有金额大于 1000 的信用卡订单
  17. db.Scopes(AmountGreaterThan1000, PaidWithCod).Find(&orders)
  18. // 查找所有金额大于 1000 的 COD 订单
  19. db.Scopes(AmountGreaterThan1000, OrderStatus([]string{"paid", "shipped"})).Find(&orders)
  20. // 查找所有金额大于1000 的已付款或已发货订单

分页

  1. func Paginate(r *http.Request) func(db *gorm.DB) *gorm.DB {
  2. return func (db *gorm.DB) *gorm.DB {
  3. page, _ := strconv.Atoi(r.Query("page"))
  4. if page == 0 {
  5. page = 1
  6. }
  7. pageSize, _ := strconv.Atoi(r.Query("page_size"))
  8. switch {
  9. case pageSize > 100:
  10. pageSize = 100
  11. case pageSize <= 0:
  12. pageSize = 10
  13. }
  14. offset := (page - 1) * perPasge
  15. return db.Offset(offset).Limit(pageSize)
  16. }
  17. }
  18. db.Scopes(Paginate(r)).Find(&users)
  19. db.Scopes(Paginate(r)).Find(&articles)

更新

  1. func CurOrganization(r *http.Request) func(db *gorm.DB) *gorm.DB {
  2. return func (db *gorm.DB) *gorm.DB {
  3. org := r.Query("org")
  4. if org != "" {
  5. var organization Organization
  6. if db.Session(&Session{}).First(&organization, "name = ?", org).Error == nil {
  7. return db.Where("organization_id = ?", org.ID)
  8. }
  9. }
  10. db.AddError("invalid organization")
  11. return db
  12. }
  13. }