【发布时间】:2021-06-29 19:46:39
【问题描述】:
我有一个产品实体,看起来像
@Entity('products')
export class productsEntity extends BaseEntity{
@PrimaryGeneratedColumn()
id: number;
//..columns
@ManyToMany( type => Categories, categoryEntity => categoryEntity.products)
categories: string;
} 然后我有一个名为 category 的实体
@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[];
}
我还有一个要验证的 DTO。
export class addProductDto{
// other DTO'S
@IsNotEmpty({ message: "category needs to be set."})
categories: Categories[];
}
现在,当我尝试在产品表中保存新产品时,除了类别列之外,一切似乎都正常。
@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)
}
}
}
我在这里做错了什么? 所有字段都会保存,但类别不会。
【问题讨论】:
标签: javascript typescript nestjs typeorm