【问题标题】:Typeorm relations query builderTypeorm 关系查询生成器
【发布时间】:2021-08-10 07:28:34
【问题描述】:

我在弄清楚如何使用 queryBuilder 从链接表中获取数据时遇到了一点问题

目前我有这个代码

const users = await databaseConntection
      .getRepository(User)
      .createQueryBuilder("user")
      .select(["images.author_id", "user.id", "user.username"])
      .leftJoinAndSelect(
        (queryBuilder) =>
          queryBuilder
            .select(["title", "updated_at", "author_id"])
            .from(Image, "image")
            .orderBy({ updated_at: "ASC" })
            .take(5),
        "images",
        "images.author_id = user.id"
      )
      .andWhere("username LIKE :profile")
      .setParameters({
        profile: `%${profile}%`,
      })
      .groupBy("images.author_id")
      .take(limit)
      .skip(page * limit - limit)
      .getRawMany();

当前结果

column "user.id" must appear in the GROUP BY clause or be used in an aggregate function

预期结果

[
   {
     "id": 1,
     "username": "some username",
     "images": [
        {
           "title": "some image title",
           "updated_at": "2021-05-21T03:49:44.299Z",
           "author_id": 1
        }
        ...rest 4 images
     ]
   }
   ...rest users
]

如何使用查询生成器实现此结果?

感谢您的帮助。

【问题讨论】:

    标签: node.js postgresql typeorm


    【解决方案1】:

    我不知道我的代码有什么问题,但我正在迁移到 prisma orm,他的工作方式与预期一样。

    这里是使用 prisma orm 的代码,这会返回预期的结果(没有 id)

    const users = await prisma.user.findMany({
          where: {
            username: {
              contains: profile as string,
            },
          },
          select: {
            username: true,
            images: {
              select: {
                title: true,
                updated_at: true,
              },
              orderBy: {
                updated_at: "asc",
              },
              take: 5,
            },
          },
          take: limit,
          skip: page * limit - limit,
        });
    

    【讨论】:

      猜你喜欢
      • 2020-07-27
      • 2023-01-20
      • 2021-10-12
      • 1970-01-01
      • 1970-01-01
      • 2022-11-09
      • 2023-01-20
      • 2021-12-18
      • 2020-09-02
      相关资源
      最近更新 更多