【问题标题】:Saving a many to many column in postgres using typeorm使用 typeorm 在 postgres 中保存多对多列
【发布时间】: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


    【解决方案1】:

    首先,您必须在 products 实体处 @JoinTable 并使用 cascades 选项通过一个保存命令保存双方最后一件事是类别的类型是 Categories[]

    @Entity('products')
    export class productsEntity extends BaseEntity{
        @PrimaryGeneratedColumn()
        id: number;
    
             //..columns
    
        @ManyToMany( type => Categories, categoryEntity => categoryEntity.products , {cascade : true ,})
        @JoinTable({name : 'products-catigories'})
    
        categories: Categories[];
    

    终于可以正常使用了

    【讨论】:

    • 我很抱歉,但它没有显示任何效果,并且做同样的事情将所有内容保存到除类别之外的产品中。
    【解决方案2】:

    如果您想导入它 => 在您的服务或存储库中使用 QueryBuilder 只需将 $ID 更改为产品 ID 或类别 ID

    import { getRepository } from "typeorm";
     
        public async getProducts(id) {
        let query = getRepository(productsEntity)
        .createQueryBuilder('product')
        .where('product.id = : id' , {id : $ID})
        .leftJoinAndSelect('product.categories' , 'catigories')
        const product = query.getOne()
        return product
    }
    
    import { getRepository } from "typeorm";
    
    public async getCatigories(id) {
        let query = getRepository(Catigories)
        .createQueryBuilder('catigory')
        .where('catigory.id = : id' , {id : $ID})
        .leftJoinAndSelect('catigory.products' , 'products')
        const product = query.getOne()
        return product
    

    【讨论】:

    • 抱歉,但不清楚您要做什么。
    【解决方案3】:

    您也可以使用查找选项及其更简单的方法

    const getOneProduct= await this.entity.findOne(id , {relations : ["categories"]})
    const getAllProducts= await this.entity.find({relations : ["categories"]})
    

    它将类别添加到产品结果中

    【讨论】:

      猜你喜欢
      • 2020-08-29
      • 2021-10-18
      • 1970-01-01
      • 2021-04-23
      • 2021-05-11
      • 2019-04-24
      • 1970-01-01
      • 2022-08-18
      • 2020-11-14
      相关资源
      最近更新 更多