20
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

TypeORMメモ

Last updated at Posted at 2019-11-20

わからなくてハマったことを追記していきたいと思っています。

元にするtableのentity

例えばサッカーチームについてのテーブル

entities/Team.ts
import {Entity, Column, OneToMany} from "typeorm"
import {Member} from "./Member"

@Entity()
export class Team {

    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string
    // 一対多
    @OneToMany(type => Member, member => member.team)
    members: Member[]
}

1対1(OneToOne)

チームに対して監督は一人と言うことで、参照される側にoneToOneを入れる
@JoinColumnは必須。

entities/HeadCoach.ts
import {Entity, Column, OneToMany} from "typeorm"
import {Member} from "./Member"

@Entity()
export class HeadCoach {

    @PrimaryGeneratedColumn()
    id: number

    @Column()
    teamId: string

    @Column()
    name: string

   // TODO selectしたい時の書き方求む
   @OneToOne(() => Team)
   // Teamテーブルの`id`を元にHeadCoachの`teamId`でjoin
   @JoinColumn([{
      name: 'teamId',
      referencedColumnName: 'id'
    }])
   team: Team;
}

1対多(OneToMany)

チームに対してメンバーが複数を表現すると

entity(多の方)
import {Entity, Column, ManyToOne} from "typeorm"
import {Team} from "./Member"

@Entity()
export class Member {

    @PrimaryGeneratedColumn()
    id?: number

    @Column()
    name?: string

    @ManyToOne(type => Team, team => team.members)
    team: Team
}
import { TeamRepository } from './repository/TeamRepository'

class TeamUsecase {
  teamRepository: TeamRepository

  constructor(
    teamRepository: TeamRepository    
  ) {
    this.teamRepository = teamRepository  
  }

  execute = (name: string) => {
    const result = await this.teamRepository.find({
      relations: ["member"],
        where: {
          name
        }
      })
  }
}

relationをネストさせたい

Teamに対するMemberとMemberの中でSeasonDataをrelationしたい。
難しく考えることなく

    const result = await this.teamRepository.find({
      relations: ["member", "member.seasonData"],
        where: {
          name
        }
      })


20
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?