Using TypeORM to Retrieve Data from Many-to-Many Relationships with Special Attributes

Hey there, I'm diving into the world of TypeORM and could really use some guidance.

I've been attempting to set up many-to-many relationships with custom properties following the instructions provided here

However, I've run into a few issues along the way.

The desired query result looks like this..

{
    "id": 1,
    "username": "John Doe",
    "products": [
        {
            "id": 1,
            "title": 'A shirt',
            "description": 'lorem ipsum'
        }
    ]
}

But unfortunately, the actual result is...

{
    "id": 1,
    "username": "John Doe",
    "products": [
        {
            "id": 1,
            "userId": 1,
            "productId":1
        }
    ]
}

This is how I'm currently querying

const user = await this.userRepository.findOne({
      where: { id },
      relations: ["products"],
});

Here is the code breakdown:

UserProduct Entity

// user-product.entity.ts

@Entity()
export class UserProduct extends BaseEntity {
  
  @PrimaryColumn()
  public id: number;

  @Column()
  public userId!: number;

  @Column()
  public productId!: number;

  @ManyToOne(
    () => User,
    (user) => user.products
  )
  public user!: User;

  @ManyToOne(
    () => Product,
    (product) => product.users
  )
  public product!: Product;

}

User Entity

// user.entity.ts

@Entity()
export class User extends BaseEntity {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  username: string;
   
  @OneToMany(()=> UserProduct, userToProduct => userToProduct.user)
  public products!: UserProduct[];

}

Product Entity

// product.entity.ts
@Entity()
export class Product extends BaseEntity {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  title: string;

  @Column({ nullable: true })
  subtitle: string;

  @Column({ nullable: true })
  description: string;


  @OneToMany(
    () => UserProduct,
    (userProduct) => userProduct.product
  )
  public users!: UserProduct[];

}

If you have any insights on achieving the desired query result, please share your thoughts!

Answer №1

If you're wondering how to load sub-relations, I've got the answer for you.

When it comes to relations, they should be loaded along with the main entity. Sub-relations can also be loaded easily (it's a shorthand for join and leftJoinAndSelect).

For more information, refer to this documentation: Find Options

To achieve this, follow this example:

const user = await this.userRepository.findOne({
      where: { id },
      relations: ["products.product"],
});

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

Ways to eliminate the blue selection box when dragging canvas objects in fabric framework

I've been trying to find a solution to remove the annoying blue highlight box that appears when dragging on the canvas while using fabric js, but so far I haven't had any luck. I've tried the following code, but it only works for text and n ...

Bump the version number and request a message for the commit

Recently diving into the world of Grunt, I've been experimenting with merging grunt-bump and grunt-prompt. My intention is to have users prompted for a commit message that will then be added to the commit. I looked to this article for guidance in str ...

Title remains consistent | Angular 4

Struggling to change the document title on a specific route. The route is initially set with a default title. { path: 'artikel/:id/:slug', component: ArticleComponent, data: {title: 'Article', routeType: RouteType.ARTICLE, des ...

The type 'undefined' cannot be assigned to the type 'string | Buffer | { key: string | Buffer; passphrase: string; } | GetPublicKeyOrSecret'

Verification Code for JWT This function is used to verify a jwt using typescript. public verify( token: string, secretOrPublicKey?: string | Buffer, options?: jwt.VerifyOptions ): Promise<object | string> { if (!secretOrPublicKey) { ...

Performing unit testing on a Vue component that relies on external dependencies

Currently, I am in the process of testing my SiWizard component, which relies on external dependencies from the syncfusion library. The component imports various modules from this library. SiWizard.vue Imports import SiFooter from "@/components/subCompon ...

Update the html() function to include any content that has been typed into a

I have a webpage structured like this: <div id="report_content"> Some information <textarea name="personal"></textarea> <b>Other information</b> <textarea name="work"></textarea> </div> Whe ...

"Headers cannot be set once they have been sent to the client... Error handling for unhandled promise rejection

Having trouble with cookies in the header - specifically, encountering an error at line number 30. The error message reads: "Cannot set headers after they are sent to the client." Additionally, there is an UnhandledPromiseRejectionWarning related to a prom ...

Can you provide guidance on how to divide a series of dates and times into an array based

Given a startDate and an endDate, I am looking to split them into an array of time slots indicated by the duration provided. This is not a numerical pagination, but rather dividing a time range. In my TypeScript code: startDate: Date; endDate: Date; time ...

How can I detect when an image is loaded in a specific container division using jQuery?

I have a container with multiple images inside, and I would like to capture an event each time an image finishes loading. For example: <div id="container"> <img src="..." /> <img src="..." /> <img src="..." /> ...

Upon deployment, Angular encounters issues with routing to lazy loaded modules

I recently completed development on a new Angular application that utilizes lazy loading for improved performance. During local testing using ng serve (or ng serve --prod to mimic production mode), the app compiled without errors and functioned properly. ...

What is the best way to incorporate animation into a React state?

Looking to implement a fade-in animation for the next index but struggling with tutorials using "react transition group" that are focused on class components or redux. const AboutTestimonials = () => { const [index, setIndex] = useState<any>(0 ...

Turn a textfield on and off in real-time

Hey everyone, I've been working on making a textfield dynamic and I wanted to share my code with you: <input type="text" id="test1" value ="dynamic" onfocus="this.disabled=true" onblur="this.disabled=false"> <input type="text" id="test2 ...

How come the likes are not being refreshed when the button is clicked in my mongoose schema?

I am currently working on an express app using nodejs and mongoose. My main goal is to implement a JavaScript function that can update the number of likes on a post in a database directly from my ejs file. However, I have encountered troubles with this tas ...

Merge various observables into a unified RxJS stream

It seems that I need guidance on which RxJS operator to use in order to solve the following issue: In my music application, there is a submission page (similar to a music album). To retrieve the submission data, I am using the query below: this.submissio ...

Is AJAX causing issues with my media uploader and color picker?

Currently, I have incorporated tabbed navigation within a WordPress admin page and it is functioning properly on its own (data can be saved). However, I am now looking to implement some AJAX functionality for toggling between pages. The issue arises when t ...

"Troubleshooting: Mongoose uniqueness feature not functioning

I am encountering an issue with mongoose where 'unique:true' is not functioning as expected. Take a look at the schema I have formulated: var mongoose = require('mongoose'); var userSchema = mongoose.Schema({ username:{ type:St ...

Encountering a type error with gatsby-plugin-dark-mode in a Typescript Gatsby setup

Issue with Layout warning in index.tsx when hovering: (alias) const Layout: ({ children }: Props) => JSX.Element import Layout Type '{ children: Element[]; }' is missing the following properties from type 'Props': theme, >toggle ...

Decorating AngularJS' ExceptionHandler with TypeScript is not feasible because a function is not identified as such

Scenario: In the project I am currently involved in, there has been a transition from utilizing AngularJS (1.6.2) with JavaScript to TypeScript 2.1.5. We had implemented a decorator on the $exceptionHandler service which would trigger a call to a common ...

I'm currently utilizing lint in my Angular 2+ project. Is there a way to arrange the constructor parameters in alphabetical order

I am struggling to organize the constructor parameters in TypeScript while using TSLINT with Angular9. I am looking for a rule similar to member-ordering that can help me sort them effectively. constructor( // Sort these private readonly router: R ...

Is there a way to retrieve a comprehensive list of all the potential routes in my nuxt.js project?

Is there a way to retrieve a list of all the potential routes in my nuxt.js project? (this would include all URLs) ...