前回
1対1の関係を保存する
データを保存してみましょう。
src/index.ts
import { AppDataSource } from "./data-source"; import { Photo } from "./entity/Photo"; import { PhotoMetadata } from "./entity/PhotoMetadata"; AppDataSource.initialize() .then(async () => { console.log("start..."); const photo = new Photo(); photo.name = "my new photo..."; photo.description = "my description..."; photo.filename = "my photo name..."; photo.views = 0; photo.isPublished = true; const photoMetadata = new PhotoMetadata(); photoMetadata.width = 555; photoMetadata.height = 777; photoMetadata.compressed = true; photoMetadata.comment = "my comment..."; photoMetadata.oriientation = "portrait"; photoMetadata.photo = photo; const photoRepository = AppDataSource.getRepository(Photo); const photoMetadataRepository = AppDataSource.getRepository(PhotoMetadata); await photoRepository.save(photo); await photoMetadataRepository.save(photoMetadata); }) .catch((error) => { console.log(error); });
実行すると、データベースは以下のようになりました。
mysql> select * from photo; +----+-----------------+-------------------+------------------+-------+-------------+ | id | name | description | filename | views | isPublished | +----+-----------------+-------------------+------------------+-------+-------------+ | 2 | my photo | my description | photo.jpg | 1 | 1 | | 3 | my photo | my description | photo.jpg | 1 | 1 | | 4 | my new photo... | my description... | my photo name... | 0 | 1 | +----+-----------------+-------------------+------------------+-------+-------------+ 3 rows in set (0.00 sec) mysql> select * from photo_metadata; +----+--------+-------+--------------+------------+---------------+---------+ | id | height | width | oriientation | compressed | comment | photoId | +----+--------+-------+--------------+------------+---------------+---------+ | 1 | 777 | 555 | portrait | 1 | my comment... | 4 | +----+--------+-------+--------------+------------+---------------+---------+ 1 row in set (0.00 sec)
まとめ
ここまでで、
- 1対1の関係を保存について
を学びました。
次回は関係の逆側を掘り下げようと思います。
コード
今回のコードは、以下に格納しました。