Skip to content

Instantly share code, notes, and snippets.

@B4nan
Last active April 30, 2019 16:24
Show Gist options
  • Select an option

  • Save B4nan/9299a15612055c5cf6847b44ae07975f to your computer and use it in GitHub Desktop.

Select an option

Save B4nan/9299a15612055c5cf6847b44ae07975f to your computer and use it in GitHub Desktop.
Using entity references in MikroORM
const book = orm.em.findOne(Book, '...');
console.log(book.author); // reference with ID only, instance of Author entity
// this will get the same reference as we already have in `book.author`
const author = orm.em.getReference(Author, book.author.id);
console.log(author.id); // accessing the id will not trigger any db call
console.log(author.isInitialized()); // false
console.log(author.name); // undefined
console.log(author === book.author); // true
// this will trigger db call, we could also use `orm.em.findOne(Author, author.id)` to do the same
await author.init();
console.log(author.isInitialized()); // true
console.log(author.name); // defined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment