Skip to content

Instantly share code, notes, and snippets.

View B4nan's full-sized avatar

Martin Adámek B4nan

View GitHub Profile
@Entity()
export class Author {
// only `name` will be considered as required for `em.create()`
[OptionalProps]?: 'createdAt' | 'updatedAt';
@PrimaryKey()
id!: number;
@Property({ defaultRaw: 'current_timestamp()' })
const god = em.create(Author, {
name: 'God', // validates required properties
email: 'god@heaven.io',
books: [{
title: 'Bible, part 1',
tags: [{ name: 'old' }, { name: 'bestseller' }],
}],
}, { persist: true }); // we can enable this globally via `persistOnCreate: true`
await em.flush();
const book = {} as Book;
const dto = wrap(book).toObject(); // EntityDTO<Book>
// this is now possible, but with the PK union type, we would need to type cast all the time
const name = dto.author.name;
import { expr } from '@mikro-orm/core';
const res1 = await em.find(Book, {
// the type argument is optional, use it to get autocomplete on the entity properties
[expr<Book>(['price', 'createdAt'])]: { $lte: [100, new Date()] },
});
// will issue query similar to this:
// select `b0`.* from `book` as `b0` where (`b0`.`price`, `b0`.`created_at`) <= (?, ?)
const book = await em.findOneOrFail(Book, 1, { populate: ['author'] });
// update existing book's author's name
wrap(book).assign({
author: {
name: 'New name...',
},
}, { updateByPrimaryKey: false });
const book = await em.findOneOrFail(Book, 1, { populate: ['author'] });
// update existing book's author's name
wrap(book).assign({
author: {
id: book.author.id,
name: 'New name...',
},
});
const res1 = await em.createQueryBuilder(Publisher).insert({
name: 'p1',
type: PublisherType.GLOBAL,
});
// res1 is of type `QueryResult<Publisher>`
console.log(res1.insertId);
const res2 = await em.createQueryBuilder(Publisher)
.select('*')
.where({ name: 'p1' })
@Entity()
export class Book {
@ManyToOne(() => Author, { wrappedReference: true })
author!: IdentifiedReference<Author>;
constructor(authorId: number) {
this.author = Reference.createFromPK(Author, authorId);
}
import { MikroORM, Utils } from '@mikro-orm/core';
await MikroORM.init({
migrations: {
path: 'dist/migrations',
pathTs: 'src/migrations',
},
// or alternatively
// migrations: {
// path: Utils.detectTsNode() ? 'src/migrations' : 'dist/migrations',
// first partially load author entities
const r1 = await em.find(Author, {}, { fields: ['id'] });
r1[0].email = 'lol'; // let's change one of the emails
console.log(r1[0].name); // undefined, not loaded
// reload full entities - no `refresh: true` needed!
const r2 = await em.find(Author, {});
console.log(r2[0]); // fully loaded author entity, but `email` is changed to 'lol'
console.log(r1[0] === r2[0]); // true, same entity instance, just updated!