Search code examples
sqlnode.jstypescriptnestjstypeorm

Conditional operator in a TypeORM request


It is necessary that the selected and Where condition does not work if the function receives 2, not 4 parameters. Maybe it had something to do with using the conditional operator you can do...

async findAllProductsByArgument(argumentId1: string, subQuery1: string, argumentId2: string, subQuery2: string): Promise<IProduct[]> {
  const qb = getRepository(Products).createQueryBuilder("products");
  const products = await qb
      .select(
          `*, 
          Products.brand_id AS brand_id`
        )
        .addSelect('brands.brand_name', 'brand_name')
        .addSelect('brands.brand_id', 'brand_nameid')
        .addSelect('categories.cat_name', 'cat_name')
        .addSelect('categories.cat_id', 'cat_id')
        .addSelect('volumes.volume_name', 'volume_name')
        .addSelect('volumes.volume_id', 'volume_id')
        .addSelect('tags.name', 'tag_name')
        .addSelect('tags.tag_id', 'tag_nameId')
        .addSelect('sub_categories.subcat_name', 'subcategory_name')
        .addSelect('sub_categories.subcat_id', 'subcategory_id')
        .addSelect('packages.package_name', 'package_name')
        .addSelect('packages.package_id', 'package_nameId')
        .addSelect('countries.country_name', 'country_name')
        .addSelect('countries.country_id', 'country_nameId')
        .addSelect('Products.price', 'price_by_one')
      .innerJoin(Brands, 'brands', 'Products.brand_id = brands.id')
      .innerJoin(Categories, 'categories', 'Products.category_id = categories.id')
      .innerJoin(Volumes, 'volumes', 'Products.volume_id = volumes.id')
      .innerJoin(Tags, 'tags', 'Products.tag_id = tags.id')
      .innerJoin(Sub_categories, 'sub_categories', 'Products.sub_category_id = sub_categories.id')
      .innerJoin(Packages, 'packages', 'Products.package_id = packages.id')
      .innerJoin(Countries, 'countries', 'Products.country_id = countries.id')
      .where('Products.stock > Products.pack_quantity AND isshow = true')
      .andWhere(`Products.${ argumentId1 } = ${ subQuery1 }`)
      //.andWhere(`Products.${ argumentId2 } = ${ subQuery2 }`) ------- Вот этот
    .getRawMany();

  return products;
}


Solution

  • if(argumentId2 && subQuery2){
      qb.andWhere(`Products.${ argumentId2 } = ${ subQuery2 }`)
    }