How to efficiently store and manage a many-to-many relationship in PostgreSQL with TypeORM

I have a products entity defined as follows:

@Entity('products')
export class productsEntity extends BaseEntity{
    @PrimaryGeneratedColumn()
    id: number;

         //..columns

    @ManyToMany( type => Categories, categoryEntity => categoryEntity.products)
    categories: string;

Next, there is an entity for categories:

@Entity('Categories')
export class Categories extends BaseEntity{
    @PrimaryGeneratedColumn()
    id: number;

    @Column({nullable: false, default: 'all', unique: true})
    title: string;

    @ManyToMany(()=> productsEntity, product => product.categories)
    products: productsEntity[];
}

Additionally, there is a DTO used for validation:

export class addProductDto{
 
     // other DTO'S

    @IsNotEmpty({ message: "category needs to be set."})
    categories: Categories[];

}

When trying to save a new product in the products table, all fields get saved correctly except for the categories column.

@EntityRepository(productsEntity)
export class productsRepository extends Repository<productsEntity> {
    private connection: Connection
    private logger = new Logger();

    async addProduct(productDetails, username){
        const {title, description, belongsTo, price, units}  = productDetails;
        try{
            let newProduct = new productsEntity();
            newProduct.title = title;
            newProduct.description = description;
            newProduct.categories = belongsTo
            newProduct.price = price;
            newProduct.units = units;
            newProduct.soldBy = username;
            await this.manager.save(newProduct);
        }
        catch(err){
            this.logger.error(err.message);
            throw new HttpException('Failed adding Product.', HttpStatus.INTERNAL_SERVER_ERROR)
        }
    }
}

What could be causing the issue with saving the categories data?

Answer №1

To begin, ensure you use the @JoinTable annotation in the products entity and include the cascades option to facilitate saving both sides with a single save command. Additionally, note that the type of categories should be an array of Categories[]

@Entity('products')
export class ProductsEntity extends BaseEntity{
    @PrimaryGeneratedColumn()
    id: number;

         //..columns

    @ManyToMany( type => Categories, categoryEntity => categoryEntity.products , {cascade : true ,})
    @JoinTable({name : 'products-catigories'})

    categories: Categories[];

Upon implementing these changes, everything should function correctly.

Answer №2

If you wish to import it, utilize QueryBuilder in your service or repository by swapping out the $ID with the product ID or category ID.

import { getRepository } from "typeorm";
 
public async getProducts(id) {
    let query = getRepository(productsEntity)
    .createQueryBuilder('product')
    .where('product.id = : id', {id: $ID})
    .leftJoinAndSelect('product.categories', 'categories')
    const product = query.getOne()
    return product
}
import { getRepository } from "typeorm";

public async getCategories(id) {
    let query = getRepository(Categories)
    .createQueryBuilder('category')
    .where('category.id = : id', {id: $ID})
    .leftJoinAndSelect('category.products', 'products')
    const product = query.getOne()
    return product

Answer №3

Another option is to utilize the find Options for a simpler approach

const findProduct= await this.entity.findOne(id , {relations : ["categories"]})
const findProducts= await this.entity.find({relations : ["categories"]})

This will include the categories in the product output

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

Encountering a discord bot malfunction while on my Ubuntu server

My discord bot runs smoothly on my Windows 10 setup, but when deployed to the server running Ubuntu Server 20, it encounters a specific error. The issue arises when trying to handle incoming chat messages from the server. While I can read and respond to m ...

The module 'angular/common' was not found in the Angular 2 TypeScript

While experimenting with a sample login form in Angular 2, I encountered an issue when trying to import 'Form_Directives' as: import { FORM_DIRECTIVES } from '@angular/common'; An error was displayed stating that the angular/common m ...

Error: The function gethostname has not been declared

I attempted to set a variable using gethostname() (1) and with $_SERVER(2), but I always receive an error message saying ReferenceError: gethostname is not defined. My goal is simply to fetch the current system name into a variable using JavaScript within ...

transferring a value from php to javascript using a form's id

I'm facing an issue where I need to pass a dynamically generated ID from a form to JavaScript. <script type="text/javascript"> $(function() { $(".button-call").click(function() { var fld = "<?= $div_id;?>"; var test = $(fld).val ...

Every instance of 'WeakMap' must include the same type parameters

While developing an Ionic App, I encountered a strange issue. Everything was running smoothly until I cloned the source code to a different machine, which resulted in an error that is displayed in the attached image. Even though there are no compilation e ...

Explore the versatile Bootstrap Table for class

Recently, I created a table with the following structure: <table id="table" class="table table-bordered table-hover"> <thead> <tr> <th data-field="id" class="hidden">ID</th> <th data-fie ...

Using the `forwardRef` type in TypeScript with JSX dot notation

Currently, I am exploring the different types for Dot Notation components using forwardRef. I came across an example that showcases how dot notation is used without forwardRef: https://codesandbox.io/s/stpkm This example perfectly captures what I want to ...

Here is how you can include a date picker with the ability to choose the day, month, and year

Can someone help me create a datepicker with options to select days, months, and years? I've been able to find resources for selecting months and years, but I'm having trouble adding the option to choose specific days. If anyone has experience ...

Extract information from a webpage using JavaScript through the R programming language

Having just started learning about web scraping in R, I've encountered an issue with websites that utilize javascript. My attempt to scrape data from a specific webpage has been unsuccessful due to the presence of javascript links blocking access to t ...

Using React: What is the best method for handling asynchronous requests to fetch a FirebaseToken and subsequently utilizing it in an API request?

My React app is interacting with an API through a Client component. Components can access the Client like this (example in the componentDidMount function of the Home page, where I retrieve a list of the user's items): componentDidMount() { let u ...

Issues with single and double quotation marks in JQuery

I'm having trouble inserting a tag into the page. The tag contains both single and double quotes, so I tried storing that part in a variable named content. Can someone explain why this content variable isn't displaying onclick after the code runs ...

Identify the currently active subitem within the item-active class in a PHP carousel slider

I am working on creating an image carousel slider with 4 items and 4 slides each. These images will act as radio buttons, and I want to highlight the slide corresponding to the selected radio button. So, when the carousel loads, the selected slide should b ...

Preparing data in the Vuex Store efficiently for an AJAX request

Dealing with a Vuex store that holds around 30 fields has been quite the challenge for me over the past couple of days. I've been struggling to properly gather the data before sending it through an AJAX post method. Being aware of the reactivity of Vu ...

Checking for Object Equality in TypeScript

I'm working on a TypeScript vector library and encountered my first failed test. The issue revolves around object equality in TypeScript/JavaScript, and despite searching through TypeScript's official documentation (http://www.typescriptlang.org ...

Guide to making an `Ajax Login` button

I am interested in creating a SIGN IN button using ajax. Specifically, I want it to display something (such as welcome) on the same page without refreshing it. This is the progress I have made so far: update2: <form id="myForm" onsubmit="return signi ...

Guide to including objects into your project without the need for babel through the use of CDN

I'm struggling with getting my Vue code to transpile properly due to some issues. I have resorted to loading Vue and other packages directly using CDN links, like this: <script src="https://cdnjs.cloudflare.com/ajax/libs/survey-vue/1.8.33/surv ...

Having trouble retrieving data from the database when passing input to a mongoose query using an href tag in Node.js

Welcome to My Schema const AutomationSchema=new mongoose.Schema( {EventName:String, EventDate:String, EventLocation:String, EventDetails:String } ) The Events Model const EventsModel=new mongoose.model("Events",AutomationSchema ...

Divide the strings within an array

When working with nodejs, I utilize walksync to obtain an array as shown below: var paths = ['Essential Classes.jade' , 'introduction.jade'] These are the filenames contained within a folder. The objective is to extract only the filen ...

Glitch in transmitting server data to client in MERN stack development

I am currently developing a MERN web application and I've encountered a bug in which the data retrieved from the server is not matching what is expected when making a GET request on the client side. Below is the controller function on the server for ...

"The interplay of Vue components: exploring the relationships, lifecycle hooks

Brand new to utilizing Vue.js. I am exploring the concept of having a single parent component and two child components that need to communicate asynchronously through Vue's event bus system. This involves using a dummy Vue object as a shared container ...