typescriptmikro-orm

MikroORM: How to set foreign key by raw id?


In MikroORM, how can you set a foreign key by its raw numeric value? For example, in Django ORM you can do this:

b = new Book()
b.author = someAuthorWithId1

and this, with raw id

b = new Book()
b.author_id = 1

How can use raw id in MikroORM?


Solution

  • 2024 update

    Nowadays (v6+) there is also the rel and ref helpers that can create unmanaged entity reference:

    const b = new Book();
    // or ref() if the relation uses Reference wrapper
    b.author = rel(Author, 1);
    

    https://mikro-orm.io/docs/entity-constructors#pojo-vs-entity-instance-in-constructor


    There are several ways:

    1. using references:
    const b = new Book();
    b.author = em.getReference(Author, 1);
    
    1. using assign helper:
    const b = new Book();
    em.assign(b, { author: 1 });
    
    1. using create helper:
    const b = em.create(Book, { author: 1 });