AllAndCount retrieves all records and the total count of records from the model. If useFieldForCount is true, it will use the fields specified in the model for counting; otherwise, it will use a constant value of 1 for counting. It returns the result as a slice of records, the total count of records
(useFieldForCount bool)
| 49 | // } |
| 50 | // fmt.Println(result, count) |
| 51 | func (m *Model) AllAndCount(useFieldForCount bool) (result Result, totalCount int, err error) { |
| 52 | // Clone the model for counting |
| 53 | countModel := m.Clone() |
| 54 | |
| 55 | // Decide how to build the COUNT() expression: |
| 56 | // - If caller explicitly wants to use the single field expression for counting, |
| 57 | // honor it (e.g. Fields("DISTINCT col") with useFieldForCount = true). |
| 58 | // - Otherwise, clear fields to let Count() use its default COUNT(1), |
| 59 | // avoiding invalid COUNT(field1, field2, ...) with multiple fields, |
| 60 | // or incorrect COUNT(DISTINCT 1) when Distinct() is set. |
| 61 | if useFieldForCount && len(m.fields) == 1 { |
| 62 | countModel.fields = m.fields |
| 63 | } else { |
| 64 | countModel.fields = nil |
| 65 | } |
| 66 | if len(m.pageCacheOption) > 0 { |
| 67 | countModel = countModel.Cache(m.pageCacheOption[0]) |
| 68 | } |
| 69 | |
| 70 | // Get the total count of records |
| 71 | totalCount, err = countModel.Count() |
| 72 | if err != nil { |
| 73 | return |
| 74 | } |
| 75 | |
| 76 | // If the total count is 0, there are no records to retrieve, so return early |
| 77 | if totalCount == 0 { |
| 78 | return |
| 79 | } |
| 80 | |
| 81 | resultModel := m.Clone() |
| 82 | if len(m.pageCacheOption) > 1 { |
| 83 | resultModel = resultModel.Cache(m.pageCacheOption[1]) |
| 84 | } |
| 85 | |
| 86 | // Retrieve all records |
| 87 | result, err = resultModel.doGetAll(m.GetCtx(), SelectTypeDefault, false) |
| 88 | return |
| 89 | } |
| 90 | |
| 91 | // Chunk iterates the query result with given `size` and `handler` function. |
| 92 | func (m *Model) Chunk(size int, handler ChunkHandler) { |