TypeORM使用Repository查询实体时如何给关联关系添加筛选条件
报错原因
你之前的写法把关联表的过滤条件用字符串拼接的形式写在顶级where配置中,TypeORM会将propertyTenants.is_active整体识别为Property实体自身的字段,自然会提示列不存在。
方案1:在关联注解中加固定过滤条件(适合每次查询该关联都需要过滤激活租户的场景)
直接在Property模型的@OneToMany注解中增加where配置即可,后续所有加载propertyTenants关联的查询都会自动带上is_active = true的过滤条件:
@OneToMany( () => PropertyTenant, (propertyTenant: PropertyTenant) => propertyTenant.property, { where: { is_active: true } } ) propertyTenants: PropertyTenant[];
修改后你的原有查询代码直接删除where中的'propertyTenants.is_active': true即可正常运行,返回的关联propertyTenants默认都是已激活的租户数据,且返回结果是实体实例,不需要额外处理。
方案2:调整查询代码实现单次过滤(适合仅本次查询需要过滤激活租户的场景)
如果你不需要全局过滤该关联,仅本次查询需要过滤,可以修改查询写法(仅支持TypeORM 0.3.x及以上版本),将关联过滤条件用对象格式传入where,关联列表用对象格式声明:
return await propertyRepository.findOne({ where: { id: id, propertyTenants: { is_active: true } }, relations: { location: { city: { state: true } }, propertyPurpose: true, propertyAmenities: { amenity: true }, propertyTenants: { tenant: true }, propertyType: true, propertyDocuments: { documentType: true }, propertyImages: true } });
这种写法不需要修改实体注解,返回结果同样是完整的实体实例,不需要额外做数据转换。
内容的提问来源于stack exchange,提问作者Ashutosh
相关产品推荐
相关产品推荐

