【问题标题】:How to filter Relations - TypeORM如何过滤关系 - TypeORM
【发布时间】:2021-02-20 02:37:27
【问题描述】:

您好,有几个关于 TypeScript 中的 TypeORM 的问题。

仅使用 Find() 我的数据库上有 2 个表。 用户和会话我想获取一个用户及其所有会话,其中 session_deleted_at 列为 NULL。

我如何获得用户?

const user = await getRepository(Users)
    .findOne({
        select: ["user_id", "user_email", "user_password"],
        relations: ["sessions"],
        where: {
            user_email: email,
            user_deleted_at: IsNull(),
        }
    })

这可以让用户正确访问user.sessions 中的所有会话,但我只想要 session_delete_at 列为 NULL 的会话。我尝试了下一个但没有工作。

const user = await getRepository(Users)
    .findOne({
        select: ["user_id", "user_email", "user_password"],
        relations: ["sessions"],
        where: {
            user_email: email,
            user_deleted_at: IsNull(),
            
            sessions: {
                session_deleted_at: IsNull()
            }
        }
    })

我一直在尝试使用 find从数据库中提取数据QueryBuilders插入/删除/更新时间>。我想这还不错......如果你有一个“让事情变得更容易”的 Find 方法,为什么还要使用 QueryBuilders。

【问题讨论】:

    标签: node.js typescript express orm typeorm


    【解决方案1】:

    如果您在 DB 表中的表列具有 idemaildeleted_at 等名称 - 下面的代码应该可以帮助您。

    const user = await getRepository(Users).createQueryBuilder('user')
      .innerJoin(Sessions, 'session') 
      .select(["user.id", "user.email", "user.password", "user.deleted_at", "session.deleted_at"])
      .where('user.email = :email', { email: <user email here> })
      .addWhere({ 'user.deleted_at': IsNull() })
      .addWhere({ 'session.deleted_at': IsNull() })
      .getOne();
    

    否则,如果您的列命名为 user_iduser_emailuser_deleted_atsession_deleted_at

    const user = await getRepository(Users).createQueryBuilder('user')
      .innerJoin(Sessions, 'session') 
      .select(["user.user_id", "user.user_email",  "user.user_password", "user.user_deleted_at", "session.session_deleted_at"])
      .where('user.user_email = :email', { email: <user email here> })
      .addWhere({ 'user.user_deleted_at': IsNull() })
      .addWhere({ 'session.session_deleted_at': IsNull() })
      .getOne();
    

    【讨论】:

      猜你喜欢
      • 2020-12-03
      • 1970-01-01
      • 2020-10-03
      • 2021-03-06
      • 2020-10-15
      • 1970-01-01
      • 2019-12-19
      • 2021-06-10
      • 1970-01-01
      相关资源
      最近更新 更多