【发布时间】:2021-04-07 10:42:58
【问题描述】:
我有一个产品实体,如下所示:
@Entity('products')
export class productsEntity extends BaseEntity{
@PrimaryGeneratedColumn()
id: number;
//...Unrealted Columns
@Column({nullable: false, unique: true})
title: string;
@ManyToMany( type => categoryEntity, category => category.products, {cascade: true, eager: true})
@JoinTable({name:"products_categories",
joinColumn: {name: 'productName', referencedColumnName: 'title'},
inverseJoinColumn: {name: 'categoryName', referencedColumnName:'title'}
})
categories: categoryEntity[];
@Column({type:"text", nullable: false})
soldBy: userEntity;
}
然后我还有一个类别实体:
@Entity('categories')
export class categoryEntity extends BaseEntity{
@PrimaryGeneratedColumn()
id: number;
@Column({nullable: false, default: 'all', unique: true})
title: string;
@ManyToMany(()=> productsEntity, product => product.categories)
products: productsEntity[];
}
由于它们具有多对多关系,因此我无法将任何内容保存到联结表中。此外,类别是预定义的,如果存在,则会在服务中进行检查。 我正在尝试这个存储库方法:
async addProduct(productDetails, username, catTitle){
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.categories.push(catTitle);
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 typeorm