【问题标题】:Search Entity by many-to-many relation and return all relations with the found Entities通过多对多关系搜索实体并返回与找到的实体的所有关系
【发布时间】:2021-11-25 17:08:32
【问题描述】:

我有两个实体:

  • 产品
  • 类别

产品和类别具有多对多关系。 看起来像这样:

{
    "id": 2,
    "title": "a product",
    "categories": [
        {
            "id": 6,
            "title": "spherical"
        },
        {
            "id": 9,
            "title": "small"
        }
    ]
}

例如,我想查找所有归类为球形的产品

现在我尝试将类别加入我的产品并使用“Where”有条件地仅获取具有匹配类别 id 的类别的产品

async findProductsByCategory(id: number): Promise<Product[]> {
    const products = await this.productRepository
    .createQueryBuilder("product")
    .leftJoinAndSelect("product.categories", "category")
    .where("category.id =:id", {id: id})
    .getMany();
    return products;
}

这仅部分有效。 搜索第 6 类产品的示例:

    {
    "id": 2,
    "title": "a product",
    "categories": [
        {
            "id": 6,
            "title": "spherical"
        }
    ]
    },
    {
    "id": 7,
    "title": "another product",
    "categories": [
        {
            "id": 6,
            "title": "spherical"
        }
    ]
    }

它只返回我想看的产品,但它也只包含我用作条件的类别关系。

有人可以帮我找到具有特定类别关系的所有产品并返回它们及其所有类别关系吗?

编辑:简化我的示例

编辑:我找到了解决方法并将其作为答案提交,如果有人对我的问题有更好的解决方案,我仍然会等待

【问题讨论】:

    标签: many-to-many nestjs typeorm


    【解决方案1】:

    我解决了这个问题,首先进行查询以获取我正在寻找的所有产品,只是为了获取它们的 id,然后进行新的查询,在其中我通过 id 获取这些产品并将它们的所有类别加入它们

        async findProductByCategory(id: number): Promise<Product[]> {
        
        const subQueryResults = await this.productRepository
            .createQueryBuilder("product")
            .select("product.id")
            .innerJoin("product.categories", "category", "category.id = :id", {id:id})
            .getMany();
    
            const products = await this.productRepository
            .createQueryBuilder("product")
            .where("product.id IN (:...subQuery)", {subQuery: subQueryResults.map(a => a.id)})
            .innerJoinAndSelect("product.categories", "category")
            .getMany();
    
            return products;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-07
      • 2021-05-25
      • 1970-01-01
      • 2012-02-19
      • 2013-04-25
      • 2012-09-29
      • 1970-01-01
      • 1970-01-01
      • 2017-06-27
      相关资源
      最近更新 更多