该方法从v2.5.0版本开始提供,用于同时查询数据记录列表及总数量,一般用于分页查询场景中,简化分页查询逻辑。

    方法定义:

    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)

    在方法内部查询总数量时,将会忽略查询中的Limit/Page操作。

    使用示例:

    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)