简体   繁体   English

如何过滤关系 - TypeORM

[英]How to filter Relations - TypeORM

Hello a couple of questions about TypeORM in TypeScript.你好,关于 TypeScript 中的 TypeORM 的几个问题。

Using only Find() I have 2 tables on my DB.仅使用 Find()我的数据库中有 2 个表。 Users & Sessions .用户和会话 I would like to get an User and all his Sessions where the column sessions_deleted_at is NULL.我想获得一个用户和他的所有会话,其中 session_deleted_at 列为 NULL。

How am I getting an User?我如何获得用户?

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

That is getting the user correctly all the sessions in user.sessions But I just want the sessions where session_delete_at column is NULL. user.sessions用户正确获取user.sessions所有会话但我只想要 session_delete_at user.sessions NULL 的会话。 I tried next but not working.我尝试了下一个但没有工作。

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()
            }
        }
    })

I am trying to use always find to pull data from the DB and QueryBuilders to Insert/Delete/Update .我试图使用 always find从数据库QueryBuilders 中提取数据Insert/Delete/Update I guess this is not Bad... Why use QueryBuilders if you have a Find method that 'make things easier'.我想这还不错...如果您有一个“使事情更容易”的 Find 方法,为什么还要使用 QueryBuilders。

If your table columns in DB tables have names like id , email , deleted_at etc. – code below should help you.如果数据库表中的表列具有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();

Else if your columns named like user_id , user_email , user_deleted_at , session_deleted_at :否则,如果您的列命名为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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM