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!