尝试创建电子商务 API。在创建 API 时,我有一条添加产品的途径。我有一个具有一种关系的普通东西的产品实体:
@Entity('products')
export class productsEntity extends BaseEntity{
@PrimaryGeneratedColumn()
id: number;
@ManyToMany(() => category, categoryEntity => categoryEntity.products, {cascade: true})
@JoinTable({name: 'product_category'})
categories: category[];
....//other columns
}
另一方面,类别实体看起来像:
@Entity('categories')
export class category extends BaseEntity{
@PrimaryGeneratedColumn()
id: number;
@Column({nullable: false, default: 'all', unique: true})
title: string;
@ManyToMany(()=> productsEntity, product => product.categories)
products: productsEntity[];
}
现在,当我尝试使用以下代码保存它时:
@EntityRepository(productsEntity)
export class productsRepository extends Repository<productsEntity> {
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.price = price;
newProduct.units = units;
newProduct.soldBy = username;
newProduct.categories = belongsTo;
await this.manager.save( newProduct );
}
catch(err){
this.logger.error(err.message);
throw new HttpException('Failed adding Product.', HttpStatus.INTERNAL_SERVER_ERROR)
}
}
}
虽然我能够保存表中不存在的产品类别字段,但中间表也没有值。并且有这样的形状。
ecommerceapi=# SELECT * FROM product_category;
见
productsId | categoriesId
------------+--------------
(0 rows)