MCPcopy Create free account
hub / github.com/mikro-orm/mikro-orm / countBy

Method countBy

packages/sql/src/SqlEntityManager.ts:181–224  ·  view source on GitHub ↗

* @inheritDoc

(
    entityName: EntityName<Entity>,
    groupBy: EntityKey<Entity> | readonly EntityKey<Entity>[],
    options: CountByOptions<Entity> = {},
  )

Source from the content-addressed store, hash-verified

179 * @inheritDoc
180 */
181 override async countBy<Entity extends object>(
182 entityName: EntityName<Entity>,
183 groupBy: EntityKey<Entity> | readonly EntityKey<Entity>[],
184 options: CountByOptions<Entity> = {},
185 ): Promise<Dictionary<number>> {
186 const em = this.getContext(false) as SqlEntityManager;
187 options = { ...options };
188 em.prepareOptions(options);
189 const meta = em.getMetadata().find(entityName)!;
190 const fields = Utils.asArray(groupBy);
191 const { where: rawWhere, ...countOptions } = options;
192
193 await em.tryFlush(entityName, options);
194 const where = await em.processWhere(entityName, rawWhere ?? ({} as FilterQuery<Entity>), options as any, 'read');
195
196 const qb = em.createQueryBuilder(meta.class);
197
198 (qb as any)
199 .select([...fields, raw('count(*) as cnt')])
200 .where(where)
201 .groupBy(fields as string[]);
202
203 if (countOptions.having) {
204 (qb as any).having(countOptions.having);
205 }
206
207 if (countOptions.schema) {
208 qb.withSchema(countOptions.schema);
209 }
210
211 const rows: any[] = await qb.execute('all', { mapResults: false });
212 const results: Dictionary<number> = {};
213
214 for (const row of rows) {
215 const keyParts = fields.map(f => {
216 const col = meta.properties[f as EntityKey<Entity>]?.fieldNames?.[0] ?? f;
217 return String(row[col]);
218 });
219 const key = keyParts.join(Utils.PK_SEPARATOR);
220 results[key] = +row.cnt;
221 }
222
223 return results;
224 }
225
226 override getRepository<T extends object, U extends EntityRepository<T> = SqlEntityRepository<T>>(
227 entityName: EntityName<T>,

Callers

nothing calls this directly

Calls 15

rawFunction · 0.90
getContextMethod · 0.80
asArrayMethod · 0.80
tryFlushMethod · 0.80
findMethod · 0.65
getMetadataMethod · 0.65
groupByMethod · 0.65
whereMethod · 0.65
selectMethod · 0.65
havingMethod · 0.65
withSchemaMethod · 0.65
executeMethod · 0.65

Tested by

no test coverage detected