What is the process of creating a typeorm relationship between orders and products?

My Orders Entity file in TypeOrm looks like this:

@Entity('orders')
export class OrdersEntity {
  @PrimaryGeneratedColumn('uuid') id: string;

  @CreateDateColumn() created: Date;

  @UpdateDateColumn() updated: Date;

  @Column('text', { default: StatusEnum.PROCESSING }) status: string;

  // relationships

  @ManyToOne(type => UsersEntity, customer => customer.orders)
  customer: UsersEntity;

  @OneToMany(type => ProductsEntity, products => products.order, {cascade: true})
  products: ProductsEntity[];
}

This is the structure of my Products Entity:

export class ProductsEntity {
  @PrimaryGeneratedColumn('uuid') id: string;

  @CreateDateColumn() created: Date;

  @UpdateDateColumn() updated: Date;

  @Column({ type: 'text', unique: true }) name: string;

  @Column('text') description: string;

  @Column('integer') unitsOnStock: number;

  @Column('numeric', { precision: 10, scale: 2 }) price: number;

  // relationships

  @ManyToOne(type => CategoriesEntity, category => category.products)
  category: CategoriesEntity;

  @ManyToOne(type => OrdersEntity, order => order.products)
  order: OrdersEntity;
}

In the orders.service.ts file, there is a function used to create new orders:

  async create(data: OrdersDto, userId: string) {
    const { productsArray } = data;
    
    const products: ProductsEntity[] = [];
    for (const productItem of productsArray) {
      const product = await this.productsRepository.findOne({
        where: { id: productItem.productId },
      });
      if (!product) {
        throw new HttpException("Product's ID not found", HttpStatus.NOT_FOUND);
      }
      if (product.unitsOnStock - productItem.quantity < 0) {
        throw new HttpException('Insufficient stock', HttpStatus.BAD_REQUEST);
      } else {
        products.push({ ...product });
      }
    }
    const user = await this.usersRepository.findOne({ where: { id: userId } });

    for (const productItem of productsArray) {
      const product = await this.productsRepository.findOne({
        where: { id: productItem.productId },
      });
      await this.productsRepository.update(product.id, {
        unitsOnStock: product.unitsOnStock - productItem.quantity,
      });
    }

    const order = await this.ordersRepository.create({
      products,
      customer: user,
    });

    await this.ordersRepository.save(order);
    return order;
  }

The goal is to have an additional column in the orders table that contains an array of objects {productId: string, quantity: string} for each order.

I attempted using @JoingTable but encountered issues...

If you have any suggestions or ideas, they would be greatly appreciated. Thank you in advance!

Answer №1

It's not efficient to handle it the way you explained. A better approach would be to create a separate table for the actual products included in an order. Here is a suggestion:

@Entity('order_items')
export class OrderItemEntity {
@PrimaryGeneratedColumn('uuid')
id: string;

@Column('uuid')
productId: string;

@Column()
quantity: number;

@ManyToOne(() => OrdersEntity, order => order.orderItems)
order: OrdersEntity;
}

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

Issues with CSS Styling not being applied properly on mobile devices in a React App deployed on Heroku

The Dilemma My React app is deployed on Heroku using create-react-app for bundling. The backend is a Node.js written in Typescript with node version 10.15.3. Locally, when I run the site using npm start, everything works perfectly. However, when I view t ...

Typescript classes fail to adhere to interface types

interface IFoo { method: (ha: string) => void; } class Foo implements IFoo { public method(ha) {} } The message displayed when hovering over the 'ha' parameter in the class method reads: Parameter 'ha' implicitly has an &apo ...

Passing Selected Table Row Model Data to Backend in Angular 7

My goal is to send the selected data in a table row, which I select through a checkbox, to the server. However, I'm unsure about how to handle this via a service call. While I have the basic structure in place, I need assistance with sending the items ...

Creating a model for a different user involves several steps that can be easily

Recently, I have been working on a project involving user interactions such as following other users and viewing their content. Using technologies like Prisma, GraphQL, and Nexus, I decided to create a following model today. The model structure is as follo ...

How to prevent redundant object declarations when passing parameters in TypeScript?

Motivation for Using Object Parameters One of the motivations behind using objects as function parameters is to allow the caller to clearly define arguments with specified field names, which can make code reviews easier. Challenge When Using Implements an ...

Angular: Exploring the possibilities of condition-based click event implementation

In my component, there are two elements: 'order information' and a 'datepicker'. When clicking on the component, it will display the order information. However, I want to prevent the click event from being triggered if the user clicks ...

How can a child component trigger an event in its parent component?

Currently, I have tabs implemented with a form and a button in tab1. In the parent component, there is an event that deactivates the current tab and activates the next one. Can anyone advise on how to call this event from the child component? gotosecond ...

Is there a way to deactivate the click function in ngx-quill editor for angular when it is empty?

In the following ngx-quill editor, users can input text that will be displayed when a click button is pressed. However, there is an issue I am currently facing: I am able to click the button even if no text has been entered, and this behavior continues li ...

Why is the ionChange/ngModelChange function being triggered from an ion-checkbox even though I did not specifically call it?

I have an issue with my code involving the ion-datetime and ion-check-box. I want it so that when a date is selected, the checkbox should automatically be set to false. Similarly, if the checkbox is clicked, the ion-datetime value should be cleared. Link ...

Calculate the sum of multiple user-selected items in an array to display the total (using Angular)

Within my project, specifically in summary.component.ts, I have two arrays that are interdependent: state: State[] city: City[] selection: number[] = number The state.ts class looks like this: id: number name: string And the city.ts class is defined as f ...

Creating a dynamic path to an imported file in React: A step-by-step guide

Struggling with a dilemma regarding dynamically generated paths for importing files in React. I have utilized the map() function to generate a dynamic part of the code, consisting of a repetitive sequence of div elements, each housing an audio element. The ...

The key provided does not correspond to a constructor object

I have a unique method that implements an interface. This is My Command. import iCommand from './i-command'; export default class Voice implements iCommand { args: String[]; message: any; client: any; config: any; constructor(a ...

Tips for testing and verifying the call to a specific Firebase method within a function using Jest

Within the file App.ts, I am utilizing the method firebase.auth().signInWithEmailAndPassword(email, password). Now, my objective is to conduct a unit test to ensure that when the myAuthenticationPlugin.authenticate(email, password) method is invoked from ...

Tips for dynamically updating localeData and LOCALE_ID for i18n websites during the build process in Angular 9

I am currently developing an application that needs to support multiple languages, specifically up to 20 different languages. The default language set for the application is en-US. The translated versions are generated successfully during the build proces ...

Using TypeScript with React: Step-by-step guide to creating a ref prop

I'm currently using Ionic with React (typescript) and working on creating my custom form builder. Within this process, I've created a form that requires a ref property for referencing purposes when in use. My challenge lies in defining a prop tha ...

Issue with retrieving JSON objects in Next.js

I've been developing a straightforward crypto price tracker using the coingecko API. At the moment, my code is unable to retrieve any of the JSON objects from the API link, and curiously, no errors or warnings are being generated to indicate what the ...

Tips for incorporating Angular2 into Eclipse using TypeScript

Recently, I delved into the world of Angular 2 and noticed that TypeScript is highly recommended over JavaScript. Intrigued by this recommendation, I decided to make the switch as well. I came across a helpful guide for setting up everything in Eclipse - f ...

Angular 6 - Accessing grandparent methods in grandchild components

I am in need of running the functions of the grandparent component: import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.cs ...

What steps can be taken to stop Internet Explorer from caching Ajax requests in Angular2 using TypeScript?

Imagine a situation where a user has 10 points. When they click a button, an ajax call is made to the server to update the user's points after they have been used. The server should send back 9 points, which is functioning correctly on all browsers ex ...

Error in Angular TypeScript occurs when attempting to read properties of an undefined value

Here is the interface that I am working with: export interface IQuest { Id: number, lat: number, lon: number, Question:string, Answer:boolean, IsDone:boolean, Correct:boolean, Range:number} Along with the following component: export class AppComponent imp ...