You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeORM查询时如何使用关联表非ID字段作为where过滤条件

TypeORM关联表非ID字段过滤方案

问题原因

TypeORM的QueryBuilder默认不会自动关联查询关联表,仅当你直接使用关联字段的ID过滤时,因为该ID是主表(User表)上存储的外键字段,所以可以直接生效。直接写user.application.token的写法会被数据库解析为对User表的application字段调用token方法,因此触发Cannot call methods on nvarchar报错。

解决方案

方案1:使用QueryBuilder显式关联表

需要先通过innerJoin(匹配同时存在关联记录的行,符合你的过滤需求)关联Application表,再对关联表的字段做过滤:

let count = await userRepo
  .createQueryBuilder("user")
  // 关联User实体的application属性,设置别名为app
  .innerJoin("user.application", "app")
  .where("user.username = :username", { username: model.username })
  // 对关联表的token字段做过滤
  .andWhere("app.token = :applicationToken", { applicationToken: model.applicationToken })
  .getCount();

方案2:使用find系列方法自动关联

如果你不需要复杂查询,用TypeORM封装的count方法更简洁,它会自动处理关联表的join逻辑:

let count = await userRepo.count({
  where: {
    username: model.username,
    // 直接嵌套写关联表的过滤条件即可
    application: {
      token: model.applicationToken
    }
  },
  // 声明要加载的关联字段
  relations: {
    application: true
  }
})

内容的提问来源于stack exchange,提问作者Alvin Stefanus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 20:15:03