[英]Entering values in a many-to-many relationship : NestJS
我有一个名为Items
的表和一个名为Categories
的表。 它们之间是多对多的关系,一个项目可以属于多个类别,一个类别可以有多个项目。
我正在使用带有 TypeORM 的 NestJS。
我的问题是在数据库中输入一个项目,并在一个请求中将它所属的多个类别传递给它。 不需要对类别执行相同的操作,因为它们已经播种在数据库中并且数量固定。
现在“解决方案”是使用已在createItemDto
中传递的categoryID
查找类别,然后在 createItem 方法中将当前项目添加到类别实体的items
数组中。
items.service.ts 中的 CreateItem 方法
async createItem(
createItemDto: CreateItemDto,
user: User,
category: Category,
): Promise<Item> {
const newItem = await this.itemsRepository.save({
name: createItemDto.name,
description: createItemDto.description,
price: createItemDto.price,
delivery: createItemDto.delivery,
cancellation: createItemDto.cancellation,
rating: createItemDto.rating,
imageUrl: createItemDto.imageUrl,
});
user.items = [...user.items, newItem];
await user.save();
category.items = [...category.items, newItem];
await category.save();
return newItem;
}
}
项目 controller.ts
@Post('/createitem')
async createItem(@Body() createItemDto: CreateItemDto): Promise<Item> {
const user = await this.authService.getUserById(createItemDto.userId);
const category = await this.categoriesService.getCategoryById(
createItemDto.categoryId,
);
return this.itemsService.createItem(createItemDto, user, category);
}
物品实体
import { Category } from './category.entity';
import { Rent } from './rent.entity';
import { User } from './user.entity';
import {
BaseEntity,
Column,
Entity,
JoinTable,
ManyToMany,
ManyToOne,
OneToOne,
PrimaryGeneratedColumn,
} from 'typeorm';
@Entity('item')
export class Item extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column()
description: string;
@Column()
price: number;
@Column()
delivery: boolean;
@Column()
cancellation: boolean;
@Column({ nullable: true })
rating: number;
@Column()
imageUrl: string;
@ManyToOne(() => User, (user) => user.items, {
onDelete: 'CASCADE',
})
user: User;
@OneToOne(() => Rent, (rent) => rent.item)
rent: Rent;
@ManyToMany(() => Category, (category) => category.items)
@JoinTable()
categories: Category[];
}
类别实体
import { Item } from './item.entity';
import {
BaseEntity,
Column,
Entity,
JoinTable,
ManyToMany,
PrimaryGeneratedColumn,
} from 'typeorm';
@Entity()
export class Category extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
category: string;
@ManyToMany(() => Item, (item) => item.categories)
items: Item[];
}
品类服务
import { Category } from './../entities/category.entity';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { CategoriesRepository } from './categories.repository';
@Injectable()
export class CategoriesService {
constructor(
@InjectRepository(CategoriesRepository)
private categoriesRepository: CategoriesRepository,
) {}
async getCategoryById(id: number): Promise<Category> {
return await this.categoriesRepository.findOne(id, {
relations: ['items'],
});
}
}
正如您所说,添加一个项目并为其分配多个类别。
首先,您应该通过使categoryId
接受类别数组来编辑createItemDto
,我们称它为categoryIds
@Post('/createitem')
async createItem(@Body() createItemDto: CreateItemDto): Promise<Item> {
const user = await this.authService.getUserById(createItemDto.userId);
const categories = await this.categoriesService.getCategoryByIds(
createItemDto.categoryIds); // Create a function accept array
//of ids, it'll has a query such as [1]
return this.itemsService.createItem(createItemDto, user, categories);
}
[1] getCategoryByIds
async getCategoryByIds(ids:Array<number>) {
return await this.categoryRepository.find({ where: { id: In(ids) }});
}
最后,在createItem
中进行一些更改
async createItem(
createItemDto: CreateItemDto,
user: User,
categories: Array<Category>, // Make the param accept list of categories
): Promise<Item> {
const newItem = await this.itemsRepository.save({
name: createItemDto.name,
description: createItemDto.description,
price: createItemDto.price,
delivery: createItemDto.delivery,
cancellation: createItemDto.cancellation,
rating: createItemDto.rating,
imageUrl: createItemDto.imageUrl,
categories : categories // you only need to assign categories from item side
});
user.items = [...user.items, newItem];
await user.save();
return newItem;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.