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

Method init

packages/core/src/entity/Collection.ts:369–435  ·  view source on GitHub ↗

Initializes the collection by loading its items from the database.

(
    options: InitCollectionOptions<TT, P> = {},
  )

Source from the content-addressed store, hash-verified

367
368 /** Initializes the collection by loading its items from the database. */
369 async init<TT extends T, P extends string = never>(
370 options: InitCollectionOptions<TT, P> = {},
371 ): Promise<LoadedCollection<Loaded<TT, P>>> {
372 if (this.#dirty) {
373 const items = [...this.#items];
374 this.#dirty = false;
375 await this.init(options);
376 items.forEach(i => this.add(i));
377
378 return this as unknown as LoadedCollection<Loaded<TT, P>>;
379 }
380
381 const em = this.getEntityManager()!;
382 options = { ...options, filters: QueryHelper.mergePropertyFilters(this.property.filters, options.filters)! };
383
384 if (options.dataloader ?? [DataloaderType.ALL, DataloaderType.COLLECTION].includes(em.config.getDataloaderType())) {
385 const order = [...this.#items]; // copy order of references
386 const orderBy = QueryHelper.mergeOrderBy(
387 options.orderBy,
388 this.property.orderBy,
389 this.property.targetMeta?.orderBy,
390 );
391 const customOrder = orderBy.length > 0;
392 const pivotTable = this.property.kind === ReferenceKind.MANY_TO_MANY && em.getPlatform().usesPivotTable();
393 const loader = await em.getDataLoader(pivotTable ? 'm:n' : '1:m');
394 const items: TT[] = await loader.load([this, { ...options, orderBy }]);
395
396 if (this.property.kind === ReferenceKind.MANY_TO_MANY) {
397 this.#initialized = true;
398 this.#dirty = false;
399
400 if (!customOrder) {
401 this.reorderItems(items, order);
402 }
403
404 return this as unknown as LoadedCollection<Loaded<TT, P>>;
405 }
406
407 this.#items.clear();
408 let i = 0;
409
410 for (const item of items) {
411 this.#items.add(item);
412 this[i++] = item;
413 }
414
415 this.#initialized = true;
416 this.#dirty = false;
417
418 return this as unknown as LoadedCollection<Loaded<TT, P>>;
419 }
420
421 const populate = Array.isArray(options.populate)
422 ? options.populate.map(f => (f === '*' ? f : `${this.property.name}.${f}`))
423 : [`${this.property.name}${options.ref ? ':ref' : ''}`];
424 const schema = this.property.targetMeta!.schema === '*' ? helper(this.owner).__schema : undefined;
425 await em.populate(this.owner as TT[], populate, {
426 refresh: true,

Callers 1

loadMethod · 0.95

Calls 13

addMethod · 0.95
getEntityManagerMethod · 0.95
reorderItemsMethod · 0.95
helperFunction · 0.85
mergePropertyFiltersMethod · 0.80
getDataloaderTypeMethod · 0.80
mergeOrderByMethod · 0.80
getPlatformMethod · 0.65
loadMethod · 0.65
clearMethod · 0.65
populateMethod · 0.65
getDataLoaderMethod · 0.45

Tested by

no test coverage detected