查询多对多关系连接表

时间:2021-04-09 06:53:23

标签: javascript database typescript typeorm

我的产品和类别实体之间存在多对多关系,如下所示:

@Entity('products')
export class productsEntity extends BaseEntity{
    @PrimaryGeneratedColumn()
    id: number;

//..other columns

    @ManyToMany( type => categoryEntity, category => category.products, {eager: true,})
    @JoinTable({name:"products_categories",
                joinColumn: {name: 'productId', referencedColumnName: 'id'},
                inverseJoinColumn: {name: 'categoryId', referencedColumnName:'id'}
              })
    categories: categoryEntity[];
}

然后我有一个类别实体:

@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: productsEntity, username, categor: categoryEntity){
        const {title, description, 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 = newProduct?.categories ?? [];
            newProduct.categories.push(categor);
            categor.products= categor?.products?? [];
            categor.products.push(newProduct);
            await newProduct.save();
            await categor.save();
            
        }
        catch(err){
            this.logger.error(err.message);
            throw new HttpException('Failed adding Product.', HttpStatus.INTERNAL_SERVER_ERROR)
        }
    }

现在除了一个问题外,一切似乎都很好:

 productId | categoryId
-----------+------------
         8 |          2
        24 |          1

如果我添加一个现有的 id,这将得到更新,而不是为新产品创建一个新行。像这样

 productId | categoryId
-----------+------------
         8 |          2
        25 |          1

我做错了什么??我找不到任何线索。

0 个答案:

没有答案