EntityManager <Driver>
Hierarchy
- EntityManager<Driver>
- EntityManager
Index
Properties
Accessors
Methods
- addFilter
- assign
- begin
- canPopulate
- clear
- clearCache
- commit
- count
- create
- createQueryBuilder
- execute
- find
- findAll
- findAndCount
- findByCursor
- findOne
- findOneOrFail
- flush
- fork
- getComparator
- getConnection
- getDriver
- getEntityFactory
- getEventManager
- getFilterParams
- getHydrator
- getKnex
- getLoggerContext
- getMetadata
- getPlatform
- getReference
- getRepository
- getTransactionContext
- getUnitOfWork
- getValidator
- insert
- insertMany
- isInTransaction
- lock
- map
- merge
- nativeDelete
- nativeUpdate
- persist
- persistAndFlush
- populate
- qb
- refresh
- refreshOrFail
- remove
- removeAndFlush
- repo
- resetTransactionContext
- rollback
- setFilterParams
- setFlushMode
- setLoggerContext
- setTransactionContext
- transactional
- upsert
- upsertMany
Properties
readonlyinherited_id
readonlyinheritedconfig
readonlyinheritedglobal
readonlyinheritedname
Accessors
inheritedid
Returns the ID of this EntityManager. Respects the context, so global EM will give you the contextual ID if executed inside request context handler.
Returns number
inheritedschema
Returns the default schema of this EntityManager. Respects the context, so global EM will give you the contextual schema if executed inside request context handler.
Returns undefined | string
Sets the default schema of this EntityManager. Respects the context, so global EM will set the contextual schema if executed inside request context handler.
Parameters
schema: undefined | null | string
Returns void
Methods
inheritedaddFilter
Registers global filter to this entity manager. Global filters are enabled by default (unless disabled via last parameter).
Parameters
name: string
cond: FilterQuery<T1> | (args: Dictionary) => MaybePromise<FilterQuery<T1>>
optionalentityName: EntityName<T1> | [EntityName<T1>]
optionalenabled: boolean
Returns void
inheritedassign
Shortcut for
wrap(entity).assign(data, { em })
Parameters
entity: Entity | Partial<Entity>
data: Data & IsSubset<EntityData<Naked, Convert>, Data>
options: AssignOptions<Convert> = {}
Returns MergeSelected<Entity, Naked, keyof Data & string>
inheritedbegin
Starts new transaction bound to this EntityManager. Use
ctx
parameter to provide the parent when nesting transactions.Parameters
options: Omit<TransactionOptions, ignoreNestedTransactions> = {}
Returns Promise<void>
inheritedcanPopulate
Checks whether given property can be populated on the entity.
Parameters
entityName: EntityName<Entity>
property: string
Returns boolean
inheritedclear
Clears the EntityManager. All entities that are currently managed by this EntityManager become detached.
Returns void
inheritedclearCache
Clears result cache for given cache key. If we want to be able to call this method, we need to set the cache key explicitly when storing the cache.
// set the cache key to 'book-cache-key', with expiration of 60s
const res = await em.find(Book, { ... }, { cache: ['book-cache-key', 60_000] });
// clear the cache key by name
await em.clearCache('book-cache-key');Parameters
cacheKey: string
Returns Promise<void>
inheritedcommit
Commits the transaction bound to this EntityManager. Flushes before doing the actual commit query.
Returns Promise<void>
inheritedcount
Returns total number of entities matching your
where
query.Parameters
entityName: EntityName<Entity>
where: FilterQuery<NoInfer<Entity>> = ...
options: CountOptions<Entity, Hint> = {}
Returns Promise<number>
inheritedcreate
Creates new instance of given entity and populates it with given data. The entity constructor will be used unless you provide
{ managed: true }
in theoptions
parameter. The constructor will be given parameters based on the defined constructor of the entity. If the constructor parameter matches a property name, its value will be extracted fromdata
. If no matching property exists, the wholedata
parameter will be passed. This means we can also defineconstructor(data: Partial<T>)
andem.create()
will pass the data into it (unless we have a property nameddata
too).The parameters are strictly checked, you need to provide all required properties. You can use
OptionalProps
symbol to omit some properties from this check without making them optional. Alternatively, usepartial: true
in the options to disable the strict checks for required properties. This option has no effect on runtime.The newly created entity will be automatically marked for persistence via
em.persist
unless you disable this behavior, either locally viapersist: false
option, or globally viapersistOnCreate
ORM config option.Parameters
entityName: EntityName<Entity>
data: RequiredEntityData<Entity, never, Convert>
optionaloptions: CreateOptions<Convert>
Returns Entity
createQueryBuilder
Creates a QueryBuilder instance
Parameters
entityName: EntityName<Entity> | QueryBuilder<Entity, never, never, never>
optionalalias: RootAlias
optionaltype: ConnectionType
optionalloggerContext: LoggingOptions
Returns QueryBuilder<Entity, RootAlias, never, never>
execute
Parameters
queryOrKnex: string | QueryBuilder<any, any> | Raw<any>
params: any[] = []
method: get | all | run = 'all'
optionalloggerContext: LoggingOptions
Returns Promise<T>
inheritedfind
Finds all entities matching your
where
query. You can pass additional options via theoptions
parameter.Parameters
entityName: EntityName<Entity>
where: FilterQuery<NoInfer<Entity>>
options: FindOptions<Entity, Hint, Fields, Excludes> = {}
Returns Promise<Loaded<Entity, Hint, Fields, Excludes>[]>
inheritedfindAll
Finds all entities of given type, optionally matching the
where
condition provided in theoptions
parameter.Parameters
entityName: EntityName<Entity>
optionaloptions: FindAllOptions<NoInfer<Entity>, Hint, Fields, Excludes>
Returns Promise<Loaded<Entity, Hint, Fields, Excludes>[]>
inheritedfindAndCount
Calls
em.find()
andem.count()
with the same arguments (where applicable) and returns the results as tuple where the first element is the array of entities, and the second is the count.Parameters
entityName: EntityName<Entity>
where: FilterQuery<NoInfer<Entity>>
options: FindOptions<Entity, Hint, Fields, Excludes> = {}
Returns Promise<[Loaded<Entity, Hint, Fields, Excludes>[], number]>
inheritedfindByCursor
Calls
em.find()
andem.count()
with the same arguments (where applicable) and returns the results as Cursor object. Supportsbefore
,after
,first
andlast
options while disallowinglimit
andoffset
. ExplicitorderBy
option is required.Use
first
andafter
for forward pagination, orlast
andbefore
for backward pagination.first
andlast
are numbers and serve as an alternative tooffset
, those options are mutually exclusive, use only one at a timebefore
andafter
specify the previous cursor value, it can be one of the:Cursor
instance- opaque string provided by
startCursor/endCursor
properties - POJO/entity instance
const currentCursor = await em.findByCursor(User, {}, {
first: 10,
after: previousCursor, // cursor instance
orderBy: { id: 'desc' },
});
// to fetch next page
const nextCursor = await em.findByCursor(User, {}, {
first: 10,
after: currentCursor.endCursor, // opaque string
orderBy: { id: 'desc' },
});
// to fetch next page
const nextCursor2 = await em.findByCursor(User, {}, {
first: 10,
after: { id: lastSeenId }, // entity-like POJO
orderBy: { id: 'desc' },
});The
Cursor
object provides the following interface:Cursor<User> {
items: [
User { ... },
User { ... },
User { ... },
],
totalCount: 50,
startCursor: 'WzRd',
endCursor: 'WzZd',
hasPrevPage: true,
hasNextPage: true,
}Parameters
entityName: EntityName<Entity>
where: FilterQuery<NoInfer<Entity>>
options: FindByCursorOptions<Entity, Hint, Fields, Excludes>
Returns Promise<Cursor<Entity, Hint, Fields, Excludes>>
inheritedfindOne
Finds first entity matching your
where
query.Parameters
entityName: EntityName<Entity>
where: FilterQuery<NoInfer<Entity>>
options: FindOneOptions<Entity, Hint, Fields, Excludes> = {}
Returns Promise<null | Loaded<Entity, Hint, Fields, Excludes>>
inheritedfindOneOrFail
Finds first entity matching your
where
query. If nothing found, it will throw an error. If thestrict
option is specified and nothing is found or more than one matching entity is found, it will throw an error. You can override the factory for creating this method viaoptions.failHandler
locally or viaConfiguration.findOneOrFailHandler
(findExactlyOneOrFailHandler
when specifyingstrict
) globally.Parameters
entityName: EntityName<Entity>
where: FilterQuery<NoInfer<Entity>>
options: FindOneOrFailOptions<Entity, Hint, Fields, Excludes> = {}
Returns Promise<Loaded<Entity, Hint, Fields, Excludes>>
inheritedflush
Flushes all changes to objects that have been queued up to now to the database. This effectively synchronizes the in-memory state of managed objects with the database.
Returns Promise<void>
inheritedfork
Returns new EntityManager instance with its own identity map
Parameters
options: ForkOptions = {}
Returns this
inheritedgetComparator
Gets the EntityComparator.
Returns EntityComparator
inheritedgetConnection
Gets the Connection instance, by default returns write connection
Parameters
optionaltype: ConnectionType
Returns ReturnType<Driver[getConnection]>
inheritedgetDriver
Gets the Driver instance used by this EntityManager. Driver is singleton, for one MikroORM instance, only one driver is created.
Returns Driver
inheritedgetEntityFactory
Gets the EntityFactory used by the EntityManager.
Returns EntityFactory
inheritedgetEventManager
Returns EventManager
inheritedgetFilterParams
Returns filter parameters for given filter set in this context.
Parameters
name: string
Returns T
inheritedgetHydrator
Gets the Hydrator used by the EntityManager.
Returns IHydrator
getKnex
Returns configured knex instance.
Parameters
optionaltype: ConnectionType
Returns Knex<any, any[]>
inheritedgetLoggerContext
Gets logger context for this entity manager.
Returns T
inheritedgetMetadata
Gets the
MetadataStorage
.Returns MetadataStorage
inheritedgetPlatform
Gets the platform instance. Just like the driver, platform is singleton, one for a MikroORM instance.
Returns ReturnType<Driver[getPlatform]>
inheritedgetReference
Gets a reference to the entity identified by the given type and identifier without actually loading it, if the entity is not yet loaded
Parameters
entityName: EntityName<Entity>
id: Entity extends { [PrimaryKeyProp]?: PK } ? PK extends keyof Entity<Entity> ? ReadonlyPrimary<UnwrapPrimary<Entity<Entity>[PK<PK>]>> : PK extends keyof Entity<Entity>[] ? ReadonlyPrimary<PrimaryPropToType<Entity<Entity>, PK<PK>>> : PK : Entity extends { _id?: PK } ? string | ReadonlyPrimary<PK> : Entity extends { uuid?: PK } ? ReadonlyPrimary<PK> : Entity extends { id?: PK } ? ReadonlyPrimary<PK> : Entity
options: Omit<GetReferenceOptions, wrapped> & { wrapped: true }
Returns Ref<Entity>
getRepository
Gets repository for given entity. You can pass either string name or entity class reference.
Parameters
entityName: EntityName<T>
Returns GetRepository<T, U>
inheritedgetTransactionContext
Gets the transaction context (driver dependent object used to make sure queries are executed on same connection).
Returns undefined | T
inheritedgetUnitOfWork
Gets the UnitOfWork used by the EntityManager to coordinate operations.
Parameters
useContext: boolean = true
Returns UnitOfWork
inheritedgetValidator
Gets EntityValidator instance
Returns EntityValidator
inheritedinsert
Fires native insert query. Calling this has no side effects on the context (identity map).
Parameters
entityNameOrEntity: Entity | EntityName<Entity>
optionaldata: Entity | RequiredEntityData<Entity>
options: NativeInsertUpdateOptions<Entity> = {}
Returns Promise<Entity extends { [PrimaryKeyProp]?: PK } ? PK extends keyof Entity<Entity> ? ReadonlyPrimary<UnwrapPrimary<Entity<Entity>[PK<PK>]>> : PK extends keyof Entity<Entity>[] ? ReadonlyPrimary<PrimaryPropToType<Entity<Entity>, PK<PK>>> : PK : Entity extends { _id?: PK } ? string | ReadonlyPrimary<PK> : Entity extends { uuid?: PK } ? ReadonlyPrimary<PK> : Entity extends { id?: PK } ? ReadonlyPrimary<PK> : Entity>
inheritedinsertMany
Fires native multi-insert query. Calling this has no side effects on the context (identity map).
Parameters
entityNameOrEntities: EntityName<Entity> | Entity[]
optionaldata: Entity[] | RequiredEntityData<Entity>[]
options: NativeInsertUpdateOptions<Entity> = {}
Returns Promise<(Entity extends { [PrimaryKeyProp]?: PK } ? PK extends keyof Entity<Entity> ? ReadonlyPrimary<UnwrapPrimary<Entity<Entity>[PK<PK>]>> : PK extends keyof Entity<Entity>[] ? ReadonlyPrimary<PrimaryPropToType<Entity<Entity>, PK<PK>>> : PK : Entity extends { _id?: PK } ? string | ReadonlyPrimary<PK> : Entity extends { uuid?: PK } ? ReadonlyPrimary<PK> : Entity extends { id?: PK } ? ReadonlyPrimary<PK> : Entity)[]>
inheritedisInTransaction
Checks whether this EntityManager is currently operating inside a database transaction.
Returns boolean
inheritedlock
Runs your callback wrapped inside a database transaction.
Parameters
entity: T
lockMode: LockMode
options: number | Date | LockOptions = {}
Returns Promise<void>
inheritedmap
Maps raw database result to an entity and merges it to this EntityManager.
Parameters
entityName: EntityName<Entity>
result: EntityDictionary<Entity>
options: { schema?: string } = {}
optionalschema: string
Returns Entity
inheritedmerge
Merges given entity to this EntityManager so it becomes managed. You can force refreshing of existing entities via second parameter. By default, it will return already loaded entities without modifying them.
Parameters
entity: Entity
optionaloptions: MergeOptions
Returns Entity
inheritednativeDelete
Fires native delete query. Calling this has no side effects on the context (identity map).
Parameters
entityName: EntityName<Entity>
where: FilterQuery<NoInfer<Entity>>
options: DeleteOptions<Entity> = {}
Returns Promise<number>
inheritednativeUpdate
Fires native update query. Calling this has no side effects on the context (identity map).
Parameters
entityName: EntityName<Entity>
where: FilterQuery<NoInfer<Entity>>
data: EntityData<Entity>
options: UpdateOptions<Entity> = {}
Returns Promise<number>
inheritedpersist
inheritedpersistAndFlush
inheritedpopulate
Loads specified relations in batch. This will execute one query for each relation, that will populate it on all the specified entities.
Parameters
entities: Entity
populate: false | AutoPath<Naked, Hint, ALL>[]
options: EntityLoaderOptions<Naked, Fields, Excludes> = {}
Returns Promise<Entity extends object[] ? MergeLoaded<ArrayElement<Entity<Entity>>, Naked, Hint, Fields, Excludes>[] : MergeLoaded<Entity, Naked, Hint, Fields, Excludes>>
qb
Shortcut for
createQueryBuilder()
Parameters
entityName: EntityName<Entity>
optionalalias: RootAlias
optionaltype: ConnectionType
optionalloggerContext: LoggingOptions
Returns QueryBuilder<Entity, RootAlias, never, never>
inheritedrefresh
Refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been persisted. Returns the same entity instance (same object reference), but re-hydrated. If the entity is no longer in database, the method returns
null
.Parameters
entity: Entity
options: FindOneOptions<Entity, Hint, Fields, Excludes> = {}
Returns Promise<null | MergeLoaded<Entity, Naked, Hint, Fields, Excludes, true>>
inheritedrefreshOrFail
Refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been persisted. Returns the same entity instance (same object reference), but re-hydrated. If the entity is no longer in database, the method throws an error just like
em.findOneOrFail()
(and respects the same config options).Parameters
entity: Entity
options: FindOneOrFailOptions<Entity, Hint, Fields, Excludes> = {}
Returns Promise<MergeLoaded<Entity, Naked, Hint, Fields, Excludes, true>>
inheritedremove
Marks entity for removal. A removed entity will be removed from the database at or before transaction commit or as a result of the flush operation.
To remove entities by condition, use
em.nativeDelete()
.Parameters
Returns this
inheritedremoveAndFlush
inheritedrepo
Shortcut for
em.getRepository()
.Parameters
entityName: EntityName<Entity>
Returns GetRepository<Entity, Repository>
inheritedresetTransactionContext
Resets the transaction context.
Returns void
inheritedrollback
Rollbacks the transaction bound to this EntityManager.
Returns Promise<void>
inheritedsetFilterParams
Sets filter parameter values globally inside context defined by this entity manager. If you want to set shared value for all contexts, be sure to use the root entity manager.
Parameters
name: string
args: Dictionary
Returns void
inheritedsetFlushMode
Parameters
optionalflushMode: FlushMode
Returns void
inheritedsetLoggerContext
Sets logger context for this entity manager.
Parameters
context: Dictionary
Returns void
inheritedsetTransactionContext
Sets the transaction context.
Parameters
ctx: any
Returns void
inheritedtransactional
Runs your callback wrapped inside a database transaction.
Parameters
cb: (em: this) => T | Promise<T>
options: TransactionOptions = {}
Returns Promise<T>
inheritedupsert
Creates or updates the entity, based on whether it is already present in the database. This method performs an
insert on conflict merge
query ensuring the database is in sync, returning a managed entity instance. The method accepts eitherentityName
together with the entitydata
, or just entity instance.// insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 41
const author = await em.upsert(Author, { email: 'foo@bar.com', age: 33 });The entity data needs to contain either the primary key, or any other unique property. Let's consider the following example, where
Author.email
is a unique property:// insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 41
// select "id" from "author" where "email" = 'foo@bar.com'
const author = await em.upsert(Author, { email: 'foo@bar.com', age: 33 });Depending on the driver support, this will either use a returning query, or a separate select query, to fetch the primary key if it's missing from the
data
.If the entity is already present in current context, there won't be any queries - instead, the entity data will be assigned and an explicit
flush
will be required for those changes to be persisted.Parameters
entityNameOrEntity: Entity | EntityName<Entity>
optionaldata: EntityData<Entity> | NoInfer<Entity>
options: UpsertOptions<Entity, Fields> = {}
Returns Promise<Entity>
inheritedupsertMany
Creates or updates the entity, based on whether it is already present in the database. This method performs an
insert on conflict merge
query ensuring the database is in sync, returning a managed entity instance. The method accepts eitherentityName
together with the entitydata
, or just entity instance.// insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 41
const authors = await em.upsertMany(Author, [{ email: 'foo@bar.com', age: 33 }, ...]);The entity data needs to contain either the primary key, or any other unique property. Let's consider the following example, where
Author.email
is a unique property:// insert into "author" ("age", "email") values (33, 'foo@bar.com'), (666, 'lol@lol.lol') on conflict ("email") do update set "age" = excluded."age"
// select "id" from "author" where "email" = 'foo@bar.com'
const author = await em.upsertMany(Author, [
{ email: 'foo@bar.com', age: 33 },
{ email: 'lol@lol.lol', age: 666 },
]);Depending on the driver support, this will either use a returning query, or a separate select query, to fetch the primary key if it's missing from the
data
.If the entity is already present in current context, there won't be any queries - instead, the entity data will be assigned and an explicit
flush
will be required for those changes to be persisted.Parameters
entityNameOrEntity: EntityName<Entity> | Entity[]
optionaldata: (EntityData<Entity> | NoInfer<Entity>)[]
options: UpsertManyOptions<Entity, Fields> = {}
Returns Promise<Entity[]>
The EntityManager is the central access point to ORM functionality. It is a facade to all different ORM subsystems such as UnitOfWork, Query Language, and Repository API.