Compare commits

...

3 Commits

Author SHA1 Message Date
alex 8cfb5d7869 where clause 2023-11-26 09:58:59 +01:00
alex c4d37d1da8 more options for where clause 2023-11-26 09:51:19 +01:00
alex 39ef3fa9e5 where clause 2023-11-26 00:24:27 +01:00
1 changed files with 21 additions and 8 deletions

View File

@ -14,7 +14,11 @@ func GetTotalPages(database *gorm.DB, paginationLimit int, any interface{}, wher
if whereQuery == nil { if whereQuery == nil {
database.Model(any). database.Model(any).
Count(&totalPages) Count(&totalPages)
} else { } else if len(args) == 0 { // here used with db.Where(&User{Name: "jinzhu", Age: 20}).First(&user)
database.Model(any).
Where(whereQuery).
Count(&totalPages)
} else { // here used with "name = ?", "jinzhu"
database.Model(any). database.Model(any).
Where(whereQuery, args). Where(whereQuery, args).
Count(&totalPages) Count(&totalPages)
@ -36,6 +40,22 @@ type PageQuery struct {
} }
func DbPageQuery(database *gorm.DB, query PageQuery, paginationLimit int, result any, orderBy string, whereQuery interface{}, args ...interface{}) *gorm.DB { func DbPageQuery(database *gorm.DB, query PageQuery, paginationLimit int, result any, orderBy string, whereQuery interface{}, args ...interface{}) *gorm.DB {
if whereQuery == nil {
return database.Limit(paginationLimit).
Offset(GetPageOffset(query.Page, paginationLimit)).
Order(orderBy).
Find(result)
}
if len(args) == 0 { // here used with db.Where(&User{Name: "jinzhu", Age: 20}).First(&user)
return database.Limit(paginationLimit).
Offset(GetPageOffset(query.Page, paginationLimit)).
Where(whereQuery).
Order(orderBy).
Find(result)
}
// here used with "name = ?", "jinzhu"
return database.Limit(paginationLimit). return database.Limit(paginationLimit).
Offset(GetPageOffset(query.Page, paginationLimit)). Offset(GetPageOffset(query.Page, paginationLimit)).
Where(whereQuery, args). Where(whereQuery, args).
@ -43,13 +63,6 @@ func DbPageQuery(database *gorm.DB, query PageQuery, paginationLimit int, result
Find(result) Find(result)
} }
func DbPageQueryWithoutWhere(database *gorm.DB, query PageQuery, paginationLimit int, result any, orderBy string) *gorm.DB {
return database.Limit(paginationLimit).
Offset(GetPageOffset(query.Page, paginationLimit)).
Order(orderBy).
Find(result)
}
// GetPage returns start and end for pagination // GetPage returns start and end for pagination
// can be used like this: robots[start:end] // can be used like this: robots[start:end]
func GetPage(lenList int, page int, limit int) (start int, end int) { func GetPage(lenList int, page int, limit int) (start int, end int) {