Relations
userRepository.find({ relations: { profile: true, photos: true, videos: true, }, }) userRepository.find({ relations: { profile: true, photos: true, videos: { videoAttributes: true, }, }, })
기본적으로 relations 옵션은 main entity와 함께 로딩 되어야 할 경우에 사용된다. 외래키가 있는 등의 상황을 말한다
즉 Sub relation들도 로딩이 되는 것인데 공식 문서에 따르면 join과 leftJoinAndSelect의 shorthand라는데, 단축어 정도로 이해했다.
위의 code는 아래의 SQL 구문으로 변환된다
SELECT * FROM "user" LEFT JOIN "profile" ON "profile"."id" = "user"."profileId" LEFT JOIN "photos" ON "photos"."id" = "user"."photoId" LEFT JOIN "videos" ON "videos"."id" = "user"."videoId" SELECT * FROM "user" LEFT JOIN "profile" ON "profile"."id" = "user"."profileId" LEFT JOIN "photos" ON "photos"."id" = "user"."photoId" LEFT JOIN "videos" ON "videos"."id" = "user"."videoId" LEFT JOIN "video_attributes" ON "video_attributes"."id" = "videos"."video_attributesId"
즉 default는 false이지만, relations로 join한 값을 출력 가능하다.
{ }로 join 한 테이블의 특정 컬럼만 접근하는 것도 가능하다
실습
@Entity() export default class User extends BaseEntity { @PrimaryGeneratedColumn({type: COLUMN_TYPE_BIGINT}) userid: number; @Column({length: 40}) nickname: string; @Column({type: COLUMN_TYPE_ENUM, enum: USER_STATUS, default: USER_STATUS.NORMAL}) status: string; // BAN, NORMAL @Column({type: COLUMN_TYPE_ENUM, enum: Gender, default: Gender.MALE}) gender: Gender; @Column({nullable: true, length: 512}) refresh_token: string; @CreateDateColumn() createdate: Date; @OneToMany(() => UserConfig, config => config.user) config: UserConfig; @OneToMany(() => UserLogin, login => login.user) login: UserLogin; @OneToMany(() => UserCampus, campus => campus.user) campus: UserCampus; }
위의 entity를 대상으로 relations 옵션을 확인해보자
- relation을 true로 하면 join 한 테이블의 값도 가져온다
export async function getUserList() { return await User.find({relations: {campus: true, login: true, config: true}}); }
- relation을 false로 하면 join 한 테이블은 참조하지 않는다
export async function getUserList() { return await User.find({relations: {campus: true, login: true, config: true}}); }
Orders
export async function getCommentList(articleid: number, {take = 10, lastid, cmtid}: {take: number; lastid?: number; cmtid?: number}) { return await Comment.find({ where: {articleid, refid: lastid && LessThanOrEqual(lastid), cmtid: cmtid && Not(cmtid)}, order: {refid: "DESC", createdate: "ASC"}, take, }); }
- order은 지정된 컬럼을 기준으로 정렬해주는 옵션이다.
- DESC, ASC로 정렬 가능하다
마치며
TypeORM이 처음이라 옵션들을 어떻게 적용하나 했는데 정형화 된 패턴이 있음을 알았다
파이썬의 dic처럼 key-value로 조건만 지정해주면 되는게 참 편리하다
'DEV > Backend' 카테고리의 다른 글
Package 'mysql-server' has no installation candidate - Ubuntu (0) | 2023.02.01 |
---|---|
Apache Could not open configuration file apache2.conf 에러 해결 (0) | 2023.01.31 |
Typeorm unique란? (0) | 2023.01.30 |
TypeORM의 Where In 절 (0) | 2023.01.30 |
Token 방식으로 로그인 구현하기 (0) | 2023.01.27 |