TypeOrm의 ManyToMany 와 JoinTable 사용하기

홍찬기
5 min readMar 29, 2019

--

ManyToMany RelationShip

ManyToMany 관계는 한 테이블의 여러 Recode 들이 다른 테이블의 여러 Recode들과 연관이 있는 경우를 말한다. 예를들어 대학교에서 학생은 여러수업을 들을수 있고 수업에 여러 학생이 있는경우 ManyToMany 관계에 있다고 말할수 있다.

Table 만들기

Student.ts

import { 
Entity ,
BaseEntity ,
PrimaryGeneratedColumn ,
Column ,
ManyToMany } from "typeorm"
import {Lecture} from "./Lecture"
@Entity({name:"student"})
export class Student extends BaseEntity{

@PrimaryGeneratedColumn()
id : number
@Column({type: "varchar"})
fistname : string
@Column({type: "varchar"})
lastname : string
@ManyToMany(type => Lecture , lectures => lectures.id , {
cascade : true
})
lectures : Lecture[];
}

Lecture.ts

import { 
Entity ,
BaseEntity ,
PrimaryGeneratedColumn ,
Column ,
ManyToMany ,
JoinTable} from "typeorm"
import {Student} from "./Student"
@Entity({name:"lecture"})
export class Lecture extends BaseEntity{

@PrimaryGeneratedColumn()
id : number
@Column({type: "varchar"})
lastname : string
@ManyToMany(type => Student , students => students.id, {
cascade : true
})
students : Student[];
}

위와 같이 Entity를 만들고 실행을 하고 데이터베이스를 확인하면 아래와같이 테이블이 생성되어 있을것이다.

여기서 student_lectures_lecture 테이블이 ManyToMany 관계로 이루어진 JoinTable이다.

TypeOrm 을 사용하여 데이터 저장하기

이제 테이블을 만들었으니 TypeOrm을 사용해 데이터를 한번 저장해 보자. TypeOrm을 쓸때 BaseEntity를 사용하면 create,update,delete 등 간단한 함수를 사용해 데이터를 생성 , 업데이트 , 삭제 할수 있다. BaseEntity를 사용하지 않으면 Query Builder함수 를 사용해야한다.

Index.ts

import { createConnection } from "typeorm";
import { Student } from "./entity/Student";
import { Lecture } from "./entity/Lecture";
createConnection().then(async connection => { await Lecture.create({ className: "TypeOrm" }).save();
await Lecture.create({ className: "Sequelize" }).save();
const lectures : any = await Lecture.find({
where: { id: 1 }
});
return lectures;
}).then(async lectures => { if (lectures) {
await Student.create({
firstName: "hong",
lastName: "gildong",
lectures: lectures //관계할 Lecture
}).save();
}
}).catch(error => console.log(error));

위와같이 만들고 npm start를 하면 Lecture 2개 Student 1개 인 데이터가 생성되고 Student를 생성할때 관계할 Lecture를 넣으면 다른 테이블에 관계가 생성된다. 실행을 했을때 아래와 같이 데이터베이스에 저장된다.

Lecture Table

Student Table

Student_Lecture JoinTable

--

--

No responses yet