Introduction

In pagination query scenarios, we often need to first call the Scan method combined with the Limit/Page chaining operation method to query the list, and then remove the Limit/Page chaining operation method to query the total count. This process is quite cumbersome, so from version v2.5.0, the framework provides the ScanAndCount method to simplify pagination query scenarios.

Example Usage

Model Query - ScanAndCount - 图1tip

The sample code is derived from business project cases and is for reference and understanding only, it cannot run independently.

Using traditional pagination query logic code:

  1. // GetList retrieves the user list of the instance.
  2. func (s sUserInfo) GetList(ctx context.Context, in model.UserInfoGetListInput) (items []entity.UserInfo, total int, err error) {
  3. items = make([]entity.UserInfo, 0)
  4. orm := dao.UserInfo.Ctx(ctx).Where(do.UserInfo{
  5. ResourceId: in.ResourceId,
  6. Status: in.Statuses,
  7. })
  8. err = orm.Order(in.OrderBy, in.OrderDirection).Limit(in.Offset, in.Limit).Scan(&items)
  9. if err != nil {
  10. return
  11. }
  12. total, err = orm.Count()
  13. return
  14. }

Using the ScanAndCount method for pagination queries:

  1. // GetList retrieves the user list of the instance.
  2. func (s sUserInfo) GetList(ctx context.Context, in model.UserInfoGetListInput) (items []entity.UserInfo, total int, err error) {
  3. items = make([]entity.UserInfo, 0)
  4. err = dao.UserInfo.Ctx(ctx).Where(do.UserInfo{
  5. ResourceId: in.ResourceId,
  6. Status: in.Statuses,
  7. }).
  8. Order(in.OrderBy, in.OrderDirection).
  9. Limit(in.Offset, in.Limit).
  10. ScanAndCount(&items, &total, false)
  11. return
  12. }

Notes

  • It is only used in scenarios where both data and total count need to be queried, generally in pagination scenarios.
  • The third parameter of ScanAndCount, useFieldForCount, indicates whether to use Fields as the parameter for Count operation. Generally, it should be false, meaning that the COUNT(1) query is performed for the total count. Passing true means using the fields of the query as the parameter for the COUNT method.