Introduction

This method has been provided since version v2.5.0 and is used for querying both the data record list and the total count, generally used in paging query scenarios to simplify paging query logic.

Method definition:

  1. // AllAndCount retrieves all records and the total count of records from the model.
  2. // If useFieldForCount is true, it will use the fields specified in the model for counting;
  3. // otherwise, it will use a constant value of 1 for counting.
  4. // It returns the result as a slice of records, the total count of records, and an error if any.
  5. // The where parameter is an optional list of conditions to use when retrieving records.
  6. //
  7. // Example:
  8. //
  9. // var model Model
  10. // var result Result
  11. // var count int
  12. // where := []interface{}{"name = ?", "John"}
  13. // result, count, err := model.AllAndCount(true)
  14. // if err != nil {
  15. // // Handle error.
  16. // }
  17. // fmt.Println(result, count)
  18. func (m *Model) AllAndCount(useFieldForCount bool) (result Result, totalCount int, err error)

When querying the total count inside the method, the Limit/Page operations in the query will be ignored.

Usage Example

  1. // SELECT `uid`,`name` FROM `user` WHERE `status`='deleted' LIMIT 0,10
  2. // SELECT COUNT(`uid`,`name`) FROM `user` WHERE `status`='deleted'
  3. all, count, err := Model("user").Fields("uid", "name").Where("status", "deleted").Limit(0, 10).AllAndCount(true)
  4. // SELECT `uid`,`name` FROM `user` WHERE `status`='deleted' LIMIT 0,10
  5. // SELECT COUNT(1) FROM `user` WHERE `status`='deleted'
  6. all, count, err := Model("user").Fields("uid", "name").Where("status", "deleted").Limit(0, 10).AllAndCount(false)