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

I am unable to integrate Autoprefixer into an Express project

I am having trouble adding Autoprefixers to the postcssmiddleware, as mentioned in the documentation here I also attempted using express-autoprefixers but still cannot see the vendors in my dest or public folder. You can find a link to my repository (node ...

Node.js retrieves a single row from a JSON array with two dimensions

I am working with a two-dimensional JSON array and I am able to retrieve data from the first dimension using data["dimension-1"], but I am struggling to access data from the second dimension using data["dimension-1"]["dimension-2"]. What is the correct m ...

Getting the Featured Image from a Post Link in Wordpress: A Step-by-Step Guide

For my Wordpress project, I have a group of links leading to inner pages, each with their own featured image. These links are created using the menu feature in Wordpress. My goal is to allow users to click on these links and have the featured image from t ...

Guide to building a react-redux application with a Node server as the backend

Hey there! I'm looking to build a react-redux app with a node server as the backend. Is it feasible for the node server to serve the react-redux app instead of having react-redux run on one port and node on another? Any suggestions on how to kick thi ...

How can I utilize a filter or pipe to populate product categories onto screens within Ionic 2?

I am considering creating an Ionic 2 app with 6 pages, but I'm unsure whether to utilize a Pipe or a Filter for the individual category pages and how to implement the necessary code. Each category page should be able to display products from the "app ...

Tips for setting up a React TypeScript project with custom folder paths, such as being able to access components with `@components/` included

I'm looking to streamline the relative url imports for my React TypeScript project. Instead of using something messy like ../../../contexts/AuthContext, I want to simplify it to just @contexts/AuthContexts. I attempted to update my tsconfig.json with ...

Receiving an error message and identifying the specific line number within the catch

try{ cause error } catch(err){ console.log(err.lineNumber) //or console.log(err.line) } The error object has various properties like err.name, err.stack, and err.message, but I have been unable to find a way to log the line number of the error ...

How can you personalize a website script by deactivating it using uBlock Origin and then reintegrating it as a userscript?

Can you imagine if it were possible to address a problematic portion of a script on a website by preventing the original script from loading, copying the source code, editing it, and then re-injecting it as a userscript with Tampermonkey? I attempted this ...

Interact with visible elements by automating mouse clicks with puppeteer

When attempting to click on various elements within a page, my goal is to do so only if they are visible. While achieving this in selenium with the is_displayed method was simple, I have struggled to find a similar approach in puppeteer. I attempted to imp ...

Finding an encrypted value using Laravel Eloquent ORM: A step-by-step guide

In my Laravel project, I am working with encrypted records using the php-encryption library before storing them in a Mysql database. Currently, when searching for a record based on an encrypted value, I loop through all the records to find a match, but thi ...

What is the best way to keep only the arrow controls visible in TransformControls translation mode?

Currently, I am using TransformControls which meets my requirements. However, it includes extra elements such as arrows and squares around the object. Is there a way to disable these additional elements and only display the arrows? https://i.sstatic.net/Lk ...

Failed to retrieve values from array following the addition of a new element

Does anyone have a solution for this problem? I recently added an element to my array using the push function, but when I tried to access the element at position 3, it wasn't defined properly processInput(inputValue: any): void { this.numOfIma ...

What sets npm run apart from npm start?

Our repository contains a substantial amount of TypeScript code that we can compile and execute using "npm run dev." This setup enables us to access the test JavaScript code via localhost. However, when examining the code in the Chrome debugger, approxim ...

The addListener method in Google Maps iterates n times for a specific number of repetitions

When looking at the code below, the GetPropBasedOnRadius(); method loops for a certain number of times. I want to call that method only when the dragging event is completed. However, I am unsure how to do this. Any assistance on this matter would be great ...

Exploring the transition from JavaScript to jQuery

Currently, I have set up an ajax request in combination with JavaScript to fetch data from an external file. The code looks like this: const ajaxRequest = new XMLHttpRequest(); const handleResponse = function() { if (ajaxRequest.readyState === 4) { ...

Is the input field not properly centered on the page?

Can someone explain why the input field is not aligning in the center? I am new to web development and need some assistance. <input type="text" id="search_bar" class="form-control" placeholder="Search" align="center"> In my CSS, I've ...

Two consecutive instances of the outcome recorded in the ajax table

I am trying to add data to a table, but one of my results is appearing twice. Here is the JSON response I received: groupname […] 0 {…} survey_id 2 group_name DEMO 1 {…} survey_id 1 group_name TEST This is what my AJAX success function ...

What techniques can I use to modify an object while it's being iterated through?

I've been attempting to manipulate the object while looping through it, but unfortunately, it's not working. How can I modify it so that the constant patient includes the property lastActivity inside the this.model array? My code looks like this ...

Using the $.each method instead of a traditional for loop

validateScaledIntegerNumberGridFields: function(frm) { var fields = $('.scaledInteger', frm); var result = true; $.each(fields, function(index) { var scale = $(this).data("scale"); ...

Integrating webpack and Vue async components from separate projects or domains

Having recently ventured into webpack, I have watched several tutorials and successfully configured it for my project. One of the challenges I encountered was loading vuejs components asynchronously using the following method: <template> <div ...