NodeJS 类型的take是否无法删除join中的重复项?(不包括Group By)

00jrzges  于 2023-04-11  发布在  Node.js
关注(0)|答案(1)|浏览(87)

我想把这个查询转换成typeorm。我尝试使用take(10),但它的行为与我的意图不同。
SELECT * FROM ( select * from Board b limit 10 ) as b left join Comment c on b.id = c.boardId
我想在一个版块上设置一个限制。不管评论的数量。但是如果你使用take,boardID会重复,如果你使用groupBy,只会输出一条评论。有什么办法吗?

8yparm6h

8yparm6h1#

我不太明白的是,如果你试图获取评论或留言板的数组。如果你要找的是留言板,你可以这样做:

const boards = await entityManager.find(Board, {
    take: 10,
    relations: { comments: true }
})

否则,您可以使用相同的查询,并进行一些后期转换:

const comments = boards.reduce((comms, board) => {
    return [...comms, ...board.comments];
    // OR, if you need the board reference inside each comment:
    // const { comments, ...boardWithoutComments } = board; // this is to avoid circular references
    // return [...comms, ...board.comments.map(com => ({ ...com, board: boardWithoutComments }))]
}, []);

我现在能想到的最后一个替代方案是使用queryBuilder按原样运行查询:

const comments = await entityManager.createQueryBuilder(Comment, "com")
    .leftJoinAndSelect("com.board", "board")
    .where("board.id IN (SELECT id FROM board LIMIT 10)")
    .getMany();

您可能希望在boards子查询中指定and order子句,并可能将其重写为第二个内部queryBuilder,以便使用参数来限制

相关问题