【发布时间】: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