@ViewEntity({
name: "post_category", // 생략 가능
expression: `
SELECT post.id AS id, post.name AS name, category.name AS categoryName
FROM post
LEFT JOIN category ON category.id = post.categoryId
`,
})
export class PostCategory {
@ViewColumn()
id: number;
@ViewColumn()
name: string;
@ViewColumn()
categoryName: string;
}
또는 QueryBuilder로도 표현 가능:
@ViewEntity({
expression: (dataSource: DataSource) =>
dataSource
.createQueryBuilder()
.select("post.id", "id")
.addSelect("post.name", "name")
.addSelect("category.name", "categoryName")
.from(Post, "post")
.leftJoin(Category, "category", "category.id = post.categoryId"),
})
where("... = :value", { value }) 형태의 파라미터 바인딩은 안 된다. 문자열 리터럴만 사용 가능.| 항목 | Entity | ViewEntity |
|---|---|---|
| 매핑 대상 | 테이블 | 뷰 (SELECT 결과) |
| 읽기/쓰기 | 읽기/쓰기 가능 | 읽기 전용 |
| 사용 목적 | 데이터 저장 및 조작 | 여러 테이블 집계, 통계 |
| 쿼리 정의 방식 | 없음 | expression으로 정의 |
Post와 Category 테이블 생성PostCategory ViewEntity 생성@ViewColumn()으로 SELECT된 값을 매핑entities: [PostCategory]로 등록 필요find() 또는 findOneBy()로 일반 엔티티처럼 조회 가능const postCategories = await dataSource.manager.find(PostCategory);
// 결과: [{ id: 1, name: "About BMW", categoryName: "Cars" }, ...]