티스토리 뷰

Backend/꾸준히 TIL

[typeorm] typeorm

개발하는 후딘 2022. 10. 25. 13:11
728x90
반응형

Querybuilder

https://typeorm.io/insert-query-builder

 


many To many 관계에서 데이터 조회/추가하기

 

https://orkhan.gitbook.io/typeorm/docs/many-to-many-relations#loading-many-to-many-relations

 

Many-to-many relations - typeorm

In case you need to have additional properties in your many-to-many relationship, you have to create a new entity yourself. For example, if you would like entities Post and Category to have a many-to-many relationship with an additional order column, then

orkhan.gitbook.io

 

@JoinTable() 은 @ManyToMany 관계에서 반드시 필수로 붙여야합니다.

주체에 해당하는 곳에 다른릴레이션을 가리키는 필드에  @JoinTable()  을 붙여야 합니다.

예를 들면 Question에는 여러개의 Category가 포함되어 있습니다.

각 질문마다 카테고리는 있을수도 있고, 없을 수도있고,  겹칠 수도 있습니다.

 

// Category

import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"

@Entity()
export class Category {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string
}

 

// Quersion 

import {
    Entity,
    PrimaryGeneratedColumn,
    Column,
    ManyToMany,
    JoinTable,
} from "typeorm"
import { Category } from "./Category"

@Entity()
export class Question {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    title: string

    @Column()
    text: string

    @ManyToMany(() => Category)
    @JoinTable()
    categories: Category[]
}

 

'질문'은 '카테고리'들을 포함하므로,

질문 안에 카테고리 필드를 넣은겁니다.

위의 코드로 typeorm 을 런타임을 실행시키면

question_catetories_category 라는 테이블을 추가하는데

이곳은 질문아이디와 카테고리 아이디 로만 구성되어 있습니다.

+-------------+--------------+----------------------------+
|                        category                         |
+-------------+--------------+----------------------------+
| id          | int(11)      | PRIMARY KEY AUTO_INCREMENT |
| name        | varchar(255) |                            |
+-------------+--------------+----------------------------+

+-------------+--------------+----------------------------+
|                        question                         |
+-------------+--------------+----------------------------+
| id          | int(11)      | PRIMARY KEY AUTO_INCREMENT |
| title       | varchar(255) |                            |
| text        | varchar(255) |                            |
+-------------+--------------+----------------------------+

+-------------+--------------+----------------------------+
|              question_categories_category               |
+-------------+--------------+----------------------------+
| questionId  | int(11)      | PRIMARY KEY FOREIGN KEY    |
| categoryId  | int(11)      | PRIMARY KEY FOREIGN KEY    |
+-------------+--------------+----------------------------+

 

 

 


https://github.com/typeorm/typeorm/blob/master/docs/relational-query-builder.md

 

GitHub - typeorm/typeorm: ORM for TypeScript and JavaScript (ES7, ES6, ES5). Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL

ORM for TypeScript and JavaScript (ES7, ES6, ES5). Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Elect...

github.com

https://github.com/typeorm/typeorm/issues/648

 

Inserting on @ManyToMany relationship · Issue #648 · typeorm/typeorm

I have one @manytomany relationship between Playlist and Song and populated the database as the following: Playlist1: [Song1, Song2, Song3] Playlist2: [Song1] Now i want to insert Song2 on the Play...

github.com

 

데이터 추가

await dataSource
    .createQueryBuilder()
    .relation(Post, "categories")
    .of({ firstPostId: 1, secondPostId: 3 })
    .add({ firstCategoryId: 2, secondCategoryId: 4 })

 

데이터 조회

post.categories = await dataSource
    .createQueryBuilder()
    .relation(Post, "categories")
    .of(post) // you can use just post id as well
    .loadMany()

https://seungtaek-overflow.tistory.com/m/11

 

[TypeORM] repository.save()의 동작과 upsert()

TypeORM에서 Data Mapper 패턴으로 repository를 이용해서 엔티티를 다루는 경우, 새로운 엔티티를 생성하고 데이터베이스에 저장할 때 repository.save() 메서드를 사용하게 된다. const newUser = new User(); await u

seungtaek-overflow.tistory.com

typeorm에서 save()는

객체가 존재하면 해당 객체와 동일한 레코드를 업데이트를하고

존재하지 않으면, 객체의 데이터를 기반으로 새로운 레코드를 등록합니다.

728x90
반응형

'Backend > 꾸준히 TIL' 카테고리의 다른 글

Git Rebase  (0) 2022.10.28
[TIL-2] NestJS + AWS RDS 시작하기  (0) 2022.10.26
[mysql] CLI 명령어로 mysql connection 부르기  (0) 2022.10.15
SSL  (0) 2022.10.15
[Node.js] node-fetch 와 ERR_REQUIRE_ESM 에러해결  (1) 2022.10.08
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함