Search code examples
javascripttypescriptpolymorphismtypeorm

TypeORM Polymorphic Relationship can not get data from parent


So I'm using https://github.com/bashleigh/typeorm-polymorphic as polymorphic relation in my model. There a few models

// Device Entity
@Entity()
@TableInheritance({ column: { type: 'varchar', name: 'type' } })
export class Device extends BaseModel { // Base model is just primary generated id and timestamp
// Device stuff
}
// lock entity
@ChildEntity()
export class Lock extends Device {
// Lock stuff

@PolymorphicChildren(()=>ConnectionData, {
        eager: false
      })
providers: ConnectionData[]
}
// connection data entity
@Entity()
@TableInheritance({ column: { type: 'varchar', name: 'type' } })
export class ConnectionData extends BaseModel  {
// connection data basic stuff
}
// first user type entity
@ChildEntity()
export class FirstUserType extends ConnectionData implements PolymorphicChildInterface {
    // other first user type stuff

    @PolymorphicParent(()=>[Lock,Key]) // Key is also a parent like lock
    connectable: Lock | Key

    @Column({name: 'connectableId'})
    entityId: string;

    @Column({name: 'connectableType'})
    entityType: string;
}

using these script

let repo = connection.getCustomRepository(FirstUserTypeRepository) // extends AbstractPolymorphicRepository

let result = repo.findOne(1) // find with some id

I'm able to get these data

{
   id: // first user type id
   prop: // first user type other properties
   connectable : {
     // Lock object
   }
}

But I want the other way. I want the output to be

{
  id: //some lock id
  data: // some lock data
  providers: [
    // I want here to be list of ConnectionData
  ]
}

I tried to create these script that I thought will be able to do such thing

let repo = connection.getCustomRepository(LockRepository) // extends AbstractPolymorphicRepository

let result = repo.findOne(1) // find with lock id

but got these error

TypeORMError: Function parameter isn't supported in the parameters. Please check "orm_param_1" parameter.

I'm not sure how would I get the data. I've been spending a few days to do so but still no luck for me until now.


Solution

  • I found out that I can use TypeOrm InnerJoinAndMap to achieve what I want, I did

     const locks = connection.getRepository(Lock)
            const result = await locks
                .createQueryBuilder("lock")
                .innerJoinAndMapMany("lock.providers",ConnectionData,"pc", `pc."connectableId"::text = lock.id::text`)
                .where({
                    id:'a725b986-71d7-4f65-bbbf-26f537c13026'
                })
                .getOne()
    

    and got the result just like what I want