How to save data in many to many relation that has custom fields in nestjs/typeorm
Here, I have created relation between cart, customer, and product entity. Relation is as follows:
Cart and Customer - OneToOne
Cart and CartProduct(Junction table for cart and product) OneToMany
Product and CartProduct(Junction table for cart and product) OneToMany
customer.entity.ts
import {
Column,
Entity,
OneToMany,
OneToOne,
PrimaryGeneratedColumn,
} from 'typeorm';
import { Cart } from './cart.entity';
@Entity()
export class Customer {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@OneToOne(() => Cart, (cart) => cart.customer)
cart: Cart;
}
cart.entity.ts
import {
Entity,
JoinColumn,
OneToMany,
OneToOne,
PrimaryGeneratedColumn,
} from 'typeorm';
import { CartProduct } from './cartProduct.entity';
import { Customer } from './customer.entity';
@Entity()
export class Cart {
@PrimaryGeneratedColumn()
id: number;
@OneToOne(() => Customer, (customer) => customer.cart)
@JoinColumn({ name: 'customerid' })
customer: Customer;
@OneToMany(() => CartProduct, (cartProducts) => cartProducts.cart)
cartProducts: CartProduct[];
}
product.entity.ts
import {
Column,
Entity,
ManyToOne,
OneToMany,
PrimaryGeneratedColumn,
} from 'typeorm';
import { Brand } from './brand.entity';
import { CartProduct } from './cartProduct.entity';
import { OrderProduct } from './orderProduct.entity';
import { SubCategory } from './subCategory.entity';
@Entity()
export class Product {
@PrimaryGeneratedColumn()
id: number;
@OneToMany(() => CartProduct, (cartProduct) => cartProduct.product)
cartProducts: CartProduct[];
}
cartProduct.entity.ts Junction table for cart and product
import { Column, Entity, ManyToOne } from 'typeorm';
import { Cart } from './cart.entity';
import { Product } from './product.entity';
@Entity()
export class CartProduct {
@Column()
quantity: number;
@ManyToOne(() => Cart, (cart) => cart.cartProducts, { primary: true })
cart: Cart;
@ManyToOne(() => Product, (product) => product.cartProducts, {
primary: true,
})
product: Product;
}
Now, while creating cart what I did is,
async addProductToCart(
customerid: number,
productid: number,
quantity: number,
): Promise<Cart> {
const customer = await this.customer.findOne({ id: customerid });
const cart = this.cart.create();
const product = await this.product.findOne({ id: productid });
cart.customer = customer;
const cartProducts = this.cartProducts.create({
cart,
product,
quantity,
});
cart.cartProducts = [cartProducts];
await this.cartProducts.save(cartProducts); //if i add this line then it
// says, NOT NULL constraint failed: cart_product.cartId
return this.cart.save(cart);
}
When I make request to this addProductToCart
function, then data don’t get stored in the database.
So, how to properly insert data using many to many relation with custom field.