I have an entity StockItem
, this contains multiple @ManyToOne
relations. There is a view called StockItemStatus
that summarises the many to one relations to a single value (e.g. list of stock changes to the current stock level).
However, in MikroORM I am unable to relate the view to the entity.
@Entity()
export class StockItem {
@PrimaryKey()
id: number;
@OneToOne(() => StockItemStatus, status => status.stockItem, { eager: true })
status: Ref<StockItemStatus>;
...
}
@Entity({ expression: 'select * from stock_item_status' })
export class StockItemStatus {
@OneToOne(() => StockItem, {
joinColumn: 'stock_item_id', // StockItemStatus.stockItemId
inverseJoinColumn: 'id' // StockItem.Id,
})
stockItem: Ref<StockItem>;
...
}
This works for all operations apart from create where I get the following error: TypeError: Cannot read properties of undefined (reading 'match')
.
I need to do this as otherwise I have ~10 @Formula
on the entity and it takes a while to load.
I am using NestJS and GraphQL and am open to otherwise to achieve this.
I also need to able to query the related properties, so using GQL field resolvers is not the solution. MikroORM needs to be aware of the relation.
I managed to do it by having stock item status as a virtual entity:
@Entity({ expression: 'select * from stock_item_status' })
export class StockItemWithStatus {
@Property()
stockItemId: number;
...
}
Then I can easily fetch it via em.findOneOrFile(StockItemWithStatus, { stockItemId: { stockItem.id })
.
Then the only other issue was filtering. But that can done via raw sql:
[raw(`(s1.id in (select stock_item_id from stock_level_current slc where slc.current_level ${hasStock ? '>' : '<='} 0))`)]: []
The only issue I can see is if the stock item table is not called s1.