【问题标题】:TypeORM Postgres filter by relation countTypeORM Postgres 按关系计数过滤
【发布时间】:2020-05-04 20:37:57
【问题描述】:

上下文 我有用户集合和食谱集合,它们之间的多对多关系

我是这个框架的新手,想知道如何进行以下查询: 计算至少有一个食谱的用户 统计没有任何食谱的用户

我发现loadRelationCountAndMap 在计算用户拥有多少食谱方面非常有用,但我似乎无法根据此属性过滤总响应。 我试过这个:

const users_without_recipes = await getRepository(User)
                .createQueryBuilder('user')
                .addSelect(['user.createdAt', 'user.email'])
                .loadRelationCountAndMap('user.recipes_count', 'user.recipes')
                .where('user.recipes_count = :count', {count: 0})
                .getManyAndCount();

也尝试使用 postgres array_count 但不确定如何将其与 typeORM 框架集成 非常感谢您的帮助

【问题讨论】:

    标签: postgresql typeorm


    【解决方案1】:

    我自己也偶然发现了这个确切的问题。我喜欢一些可以帮助您找到解决方案的资源。您的潜在问题更为普遍。如果您打开日志记录,您可能会看到类似以下的错误消息:
    错误列“用户”。“recipes_count”不存在
    问题是您正在尝试使用别名。这个问题处理这个问题: Using an Alias in a WHERE clause

    我希望你比我更成功,但我决定在日志反复试验后使用一种解决方法。我确信有更好的方法。如果您设法找到它,请告诉我。
    (如果您想取回用户实体列表,不带 user.recipes_count 属性,请同时包含最后一个 .map。)

    const users_without_recipes =  await getRepository(User)
    .createQueryBuilder('user')
    .loadRelationCountAndMap('user.recipes_count', 'user.recipes')
    .getMany();
    
    return users_without_recipes 
        .filter((user) => user['user.recipes_count'] === 0)
        .map(({recipes_count, ...otherProperties}) => otherProperties);
    

    【讨论】:

      【解决方案2】:

      我认为你可以使用子查询来做到这一点。

      在 SQL 中是这样的:

      SELECT *
      // ... other stuff
      WHERE user.id IN (
          SELECT u.id
          FROM user u JOIN recipie r USING(id)
          GROUP BY u.id
          HAVING COUNT(*) > 10
      )
      

      或者在 TypeORM 中:

      // ...
      .where(qb => {
          const subQuery = qb.subQuery()
              .select("u.id")
              .from(User, "u")
              // join users and recipies 
              .groupBy("u.id")
              .having("COUNT(*) > :count", { count: 10 })
              .getQuery();
          return "user.id IN " + subQuery;
      });
      //...
      

      【讨论】:

        猜你喜欢
        • 2021-02-20
        • 2020-10-03
        • 2020-12-03
        • 2021-07-21
        • 2021-03-06
        • 2020-10-15
        • 1970-01-01
        • 2021-12-16
        • 1970-01-01
        相关资源
        最近更新 更多