TypeORM's Polymorphic Relationship fails to retrieve data from the parent entity

Currently, I am utilizing https://github.com/bashleigh/typeorm-polymorphic for handling polymorphic relations in my model. There are several models involved:

// Device Entity
@Entity()
@TableInheritance({ column: { type: 'varchar', name: 'type' } })
export class Device extends BaseModel { // Base model consists of primary generated id and timestamp
// Device specific code here
}
// Lock entity
@ChildEntity()
export class Lock extends Device {
// Lock specific code here

@PolymorphicChildren(()=>ConnectionData, {
        eager: false
      })
providers: ConnectionData[]
}
// Connection Data entity
@Entity()
@TableInheritance({ column: { type: 'varchar', name: 'type' } })
export class ConnectionData extends BaseModel  {
// Basic connection data functionality
}
// First User Type entity
@ChildEntity()
export class FirstUserType extends ConnectionData implements PolymorphicChildInterface {
    // Additional First User Type properties

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

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

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

By implementing the following code snippet:

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

let result = repo.findOne(1) // fetching data based on an ID

I am able to retrieve the aforementioned data. However, I aim to achieve a different output:

{
   id: // represents first user type ID
   prop: // other properties related to first user type
   connectable : {
     // Lock object information
   }
}

My desired output structure should look like this:

{
  id: // some lock ID
  data: // additional lock data
  providers: [
    // List of ConnectionData entities should be included here
  ]
}

In an attempt to accomplish this, I crafted a script that I believed would fulfill the requirement:

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

let result = repo.findOne(1) // searching for a lock by its ID

However, when executing the above code, the following error occurred:

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

I have been investing time and effort over the past few days to resolve this issue, but unfortunately, I have not yet managed to find a solution.

Answer №1

After discovering the power of TypeOrm's InnerJoinAndMap, I successfully implemented it to achieve my desired outcome.

 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()

The end result matched exactly what I was aiming for.

Answer №2

The issue arises as a result of a flaw in the software package. To address this, I have put together a pull request to rectify the problem.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for setting up Craigslist email forwarding through Node.js (receiving emails to a dynamically generated email address and redirecting them)

After extensive searching, I only came across this Stack Overflow post about Email Forwarding like Craigslist in Rails: Email Forwarding like Craigslist - Rails I spent a significant amount of time googling, but couldn't find any solutions using Node ...

Is there a way to retrieve the current logged in user when working with socket.io?

When it comes to retrieving the logged in user using passport.js in most of my routes, it's a breeze - just use req.user.username. However, I've encountered an issue with a page that relies solely on websockets. How can I determine the username o ...

Paper.js - generate a collection of movable shapes

I am attempting to use paper.js to create draggable shapes where the index of each shape is provided during dragging. Unfortunately, I keep encountering an error that says "Uncaught TypeError: Cannot read property 'position' of undefined". If a ...

Using AngularJS, deleting items by their $index with ng-repeat

I'm currently working with two directives: a query builder and a query row. The query builder directive utilizes ng repeat to display query rows from an array. While the add button functions properly, I am looking to add a delete button as well. Howev ...

v-autocomplete no selected option

Within my Vue.js 2 and Vuetify component, I am receiving the following data : [ { "anio": 2022, "__typename": "Grupo" }, { "anio": 2020, "__typename": "Grupo" }, { "anio": 2018, "__ ...

How can I leverage Express, AngularJS, and Socket.io to facilitate broadcasting and receiving notifications?

A new notification system is in the works. To illustrate, User 1 is initiating a friend request to User 2. The technologies being utilized include express.js, angularjs, and socket.io. When User1 clicks the button, a request is sent. On User2's end, a ...

Error TS6200 and Error TS2403: There is a conflict between the definitions of the following identifiers in this file and another file

Currently working on setting up a TypeScript node project and running into issues with two files: node_modules@types\mongoose\index.d.ts node_modules\mongoose\index.d.ts Encountering conflicts in the following identifiers when trying ...

Generate a fresh FileReader instance using the downloaded file via XmlHTTPRequest

I am attempting to use an XmlHTTPRequest object (level 2) downloaded through a "GET" request in order to create a new FileReader object. My goal is to create the FileReader object within the onload function of the xhr. The file, which is a .gz file, downl ...

Type validation in TypeScript through cross-referencing variables

Can TypeScript be used to define a variable that determines the type of other variables? I want to simplify the process by only needing to check one variable, stateIndicator, which is dependent on other variables to infer their types. type A = {prop1: st ...

Verify if session is in existence

Currently in the process of setting up my NodeJS and Express App, utilizing Passport for authentication through Google Sign In and Login. All functionalities work flawlessly when tested on localhost. The sign-in process is smooth, and upon checking, I can ...

Express.static is having difficulty serving the JSON file

I have a series of inquiries: Currently, I am in the process of developing an application using Angular and Node (Express). 1) Within my Node server, I am serving all static files from my 'static_dir' app.use(express.static(STATIC_DIR)); Insi ...

How can one implement closure in Angular 4?

I am looking to implement a nested function within another function in Angular 4 for closure. However, when attempting the code below, I encounter an error stating "cannot find name innerFn" outerFn(){ let a = "hello"; innerFn(){ console.log(a ...

Display Image After Uploading with AJAX

After spending nearly 3 hours working on implementing file uploads via AJAX, I have finally managed to get it up and running smoothly. Take a look at the code below: View <div class="form-horizontal"> <div class="form-group"> @Htm ...

Create a bookmark system on an HTML page by utilizing the existing heading tags and implementing Javascript

Looking to implement a bookmark system using the headings within my HTML document, based on heading hierarchy. Unfortunately, my attempts have not been successful so far. https://i.stack.imgur.com/CdXjw.png I envision my bookmarks looking something like t ...

React Redux component fails to reflect changes in props after store update

Something odd is happening with my React Native component's props. They used to update after the redux store updated, but suddenly one day they stopped working. The dispatch is functioning correctly, and the store is updating state without any mutati ...

Updating numerous records with varying values

Utilizing jQuery UI's sortable feature (source) allows me to rearrange elements effortlessly. By implementing custom callbacks, I can generate a list of these elements, assigning each a new position ID as I move them around. The resulting list may app ...

Displaying iterative content using Vue.js from an array of items

Looking to style questions and answers differently when rendering them. The data structure is as follows: dialogTut:{ mainTab:{ q:"data with 42 people?", a:"hehe", q:"Are awesome people?", a:"sometimes", ...

Is it possible to refresh a div on one .aspx page using content from another .aspx page?

Just beginning my journey with asp.net and currently tackling a project that involves two .aspx pages. Events.aspx: This page is where the site admin can update upcoming events and webinars using an available panel to input event title, date, information ...

What is the reason behind Typescript not narrowing generic union type components when they are eliminated by type guards?

Consider the following scenario where type definitions and function implementations are provided: interface WithNumber { foo: number; } interface WithString { bar: string; } type MyType = WithNumber | WithString; interface Parameter<C extends My ...

What Causes the Undefined Value of "this" in Vue 3 Functions?

Here is a basic example of a component in Vue 3: <script> import { defineComponent } from 'vue' export default defineComponent({ name: 'Test', setup(){ return{ one, two } } }) function one(){ console. ...