前回
モデルの作成
ステップバイステップで進んでみましょう。
データベースの操作は、テーブルの作成から始まります。
テーブル = モデルです。
モデルを作成してみます。
src/entity/Photo.ts
export class Photo { id: number; name: string; description: string; filename: string; views: number; isPublished: boolean; }
エンティティの作成
エンティティは@Entity
デコレータで装飾されたモデルです。
モデルをエンティティに修正します。
src/entity/Photo.ts
import { Entity } from "typeorm"; @Entity() export class Photo { id: number; name: string; description: string; filename: string; views: number; isPublished: boolean; }
テーブル列の追加
データベースの列を追加するには、列にしたいエンティティのプロパティを@Column
デコレータで装飾します。
エンティティにテーブル列を追加してみます。
src/entity/Photo.ts
import { Column, Entity } from "typeorm"; @Entity() export class Photo { @Column() id: number; @Column() name: string; @Column() description: string; @Column() filename: string; @Column() views: number; @Column() isPublished: boolean; }
データベースの列の型は、使用したプロパティの型から推測されます。
numberはintegerに、stringはvarcharに、booleanはboolなどに変換されます。
ただし、@Column
デコレータに列タイプを明示的に指定することで、任意の列タイプを使用できます。
プライマリ列の追加
各エンティティには、少なくとも一つのプライマリ列が必要です。
プライマリ列にするには、@PrimaryColumn
デコレータで装飾します。
エンティティにプライマリ列を追加してみます。
src/entity/Photo.ts
import { Column, Entity, PrimaryColumn } from "typeorm"; @Entity() export class Photo { @PrimaryColumn() id: number; @Column() name: string; @Column() description: string; @Column() filename: string; @Column() views: number; @Column() isPublished: boolean; }
自動生成列の追加
自動生成列を追加するには、@PrimaryGeneratedColumn()
デコレータで装飾します。
エンティティに自動生成列を追加してみます。
src/entity/Photo.ts
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm"; @Entity() export class Photo { @PrimaryGeneratedColumn() id: number; @Column() name: string; @Column() description: string; @Column() filename: string; @Column() views: number; @Column() isPublished: boolean; }
列のデータ型
それぞれのカラムでデータ型を指定してみます。
src/entity/Photo.ts
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm"; @Entity() export class Photo { @PrimaryGeneratedColumn() id: number; @Column({ length: 100 }) name: string; @Column("text") description: string; @Column() filename: string; @Column("double") views: number; @Column() isPublished: boolean; }
まとめ
ここまでで、
- モデルの作成について
- エンティティの作成について
- テーブル列の追加について
- プライマリ列の追加について
- 自動生成列の追加について
- 列のデータ型について
を学びました。
次回はDataSourceから掘り下げようと思います。
コード
今回のコードは、以下に格納しました。