Search code examples
node.jsnestjsmikro-orm

How can we populate (or load) a 1:1 relationship from inside a entity class in MikroORM?


just some quick background: We have a Menu entity which has a 1:1 with MenuActiveHours entity. The MenuActiveHours holds information regarding the time the Menu is to be active throughout all 7 days of the week.

{
    "monday": "1200-1400",
    "tuesday": "",
     ...
]

And the Menu entity has a "status" property which is not persisted and it is calculated by checking if there is any day it has some hours active.

In the Menu.entity.ts we have:

    @Property({
        persist: false,
      })
      get status() {
        if(this.activeHours) {
         return 
this.activeHours.getActiveHoursAsArray().filter((day) => day.hours != "").length > 0 ? MENU_BUILDER_STATUS.ACTIVE : MENU_BUILDER_STATUS.NOT_ACTIVE
        }    
    
        
        return "No status given"
      }

This works fine if the entity of "activeHours" is actually populated. But its not, and in our case we cant populate it in the service either. So for example if it was a 1:M we could just .loadItems() and then getitems() and it loads it but i cant seem to figure out how to load the 1:1 inside the entity.

Easily put: How can we load a 1:1 relationship inside a function inside a entity? And am i trying to set the status from a wrong point of view and should maybe use something like intercepters instead?


Solution

  • Loading things is async operation, so you can't do that from inside a getter.

    To load an entity you can do wrap(entity).init(). Alternatively, you can also use Reference wrapper which has load() method.

    https://mikro-orm.io/docs/entity-references#better-type-safety-with-referencet-wrapper