반응형
 const jointest = await DB.getRepository(Post)
    .createQueryBuilder("post")
    .leftJoinAndSelect("post.imageFiles", "imageFiles.url")
    .where("post.id <= :id", { id: readedPostId })
    .orderBy({ "post.id": "DESC" })
    .limit(50)
    .getMany();

typeOrm으로 leftjoin후 50개의 객체를 리턴받는 것을 목표로 쿼리를 작성했지만

실제로는 객체가 50개가 리턴되지 않고 적은 숫자가 리턴되었다.

 

그 이유는 이렇게 쿼리를 작성하면 

실제 쿼리는 위의 사진과 같이 Post id가 여러개 중복된 결과를 바탕으로

객체를 만들어서 리턴해주기 때문에

즉 쿼리 결과 50개를 바탕으로 객체를 리턴해주어서 post 50개가 아닌 쿼리결과 50개에 해당하는 데이터를 받는 것이었다.

 

이런 문제를 해결하기 위해서는 조인 후 리밋을 거는 게 아니라

post에 미리 50개를 리밋 걸어서 얻고 그 후 조인을 해야 해결할 수 있다.

 

실제 쿼리문으로 치면 이런식으로 작성을 해야 하는 것이다.

select * from (select id, writer from post order by post.id desc limit 50) as post
left join image_file
on post.id = image_file.postId

 

 

그런데 검색을 하다보니 limit이 아닌 take를 사용하면 이 문제를 해결 할 수 있었다. 

const jointest = await DB.getRepository(Post)
    .createQueryBuilder("post")
    .where("post.id <= :id", { id: readedPostId })
    .orderBy({ "post.id": "DESC" })
    .leftJoinAndSelect("post.imageFiles", "imageFiles.url")
    .take(50)
    .getMany();

typeOrm pagination

https://orkhan.gitbook.io/typeorm/docs/select-query-builder#adding-offset-expression

 

Select using Query Builder - typeorm

There are two types of results you can get using select query builder: entities and raw results. Most of the time, you need to select real entities from your database, for example, users. For this purpose, you use getOne and getMany. However, sometimes you

orkhan.gitbook.io

 

+ Recent posts