Develop/[NestJs]
[NestJs] 매핑 테이블 엔티티 생성 및 사용
HiSmith
2023. 7. 3. 21:13
반응형
엔티티간의 다대다 관계인 경우, 해당 매핑 테이블을 생성하는 것이 좋은데
매핑 테이블을 엔티티로 선언하는 것보다, 해당 역할을 하는 엔티티를 생성하는 것이 좋다.
1) 매핑 엔티티
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn, JoinColumn, OneToOne, ManyToOne } from 'typeorm';
import { Member } from 'src/member/entities/member.entity';
import { Campaign } from 'src/campaign/entities/campaign.entity';
import { CampaignMemberResDto } from '../dto/campaign-member.res.dto';
import { Exclude } from 'class-transformer';
@Entity()
export class CampaignMember {
@PrimaryGeneratedColumn()
@Exclude({ toPlainOnly: true })
id: number
@ManyToOne(() => Member, {
onDelete: 'CASCADE', // decide on delete logic
eager: true
})
member: Member;
@ManyToOne(() => Campaign, {
onDelete: 'CASCADE', // decide on delete logic
eager: true
})
campaign: Campaign;
@Column()
authCode: number;
makeResponse() :CampaignMemberResDto{
return new CampaignMemberResDto(this);
}
}
2) 기존 엔티티 수정 예시 (campaignMember 추가)
import { Corp } from 'src/corp/entities/corp.entity';
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn, JoinColumn, OneToOne, ManyToOne, Generated, OneToMany } from 'typeorm';
import { IsEmail, IsNumber } from 'class-validator';
import { MemberReqDto } from '../dto/member.req.dto';
import { Schedule } from 'src/schedule/entities/schedule.entity';
import { CampaignMember } from 'src/campaign-member/entities/campaign-member.entity';
@Entity()
export class Member {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column(IsEmail)
email: string;
@Column()
name: string;
@Column()
nickname: string;
@Column(IsNumber)
phoneNumber: number;
@Column({default: ''})
deviceInfo: string;
@CreateDateColumn()
regdate : Date; //생성일자
@Column()
authCode: number;
@OneToMany(() => Schedule, (schedule) => schedule.member)
schedule: Schedule[]
@Column()
password: string;
@OneToMany(() => CampaignMember, campainMember => campainMember.member, {
nullable: true,
cascade: true,
})
campaignMember: CampaignMember[];
constructor(input?: MemberReqDto, member?: Member){
if(input){
this.name = input.name;
this.nickname = input.nickname;
this.email = input.email;
this.phoneNumber = input.phoneNumber;
this.authCode = input.authCode;
this.password = input.password;
if(this.deviceInfo){
this.deviceInfo= input.deviceInfo;
}
}
}
}
3) queryBuilder로 해당 데이터 조회 select 뒤에, leftJoin이나 별도 조인설정을 줄 수도있다.
async findMemberList(id: number): Promise<CampaignMember[]> {
return await this.campaignRepository.createQueryBuilder('campaign_member')
.select('memberId,campaignId,authCode')
.where('campaign_member.campaignId = :id',{id: id})
.getRawMany();
}
}
결과
반응형