メモ:Sequelize

2020年11月22日

前回からの続きです。

SequelizeはNode.js用のORMライブラリです。SQLiteを直接扱うのをやめ、Sequelizeを使うことにしました。

ここまでの作業をGitHubにおいています。

sequelize と一緒に sequelize-cli というライブラリを使うと、 以下のようなコマンドを実行できます。

  • 初期化コマンド(init)
    • 必要なファイル、ディレクトリが生成される。
      • config/config.json
      • models/index.js
      • migrations/
      • seeders/
  • モデルの作成(model:create)
  • マイグレーション
  • 初期データ投入

以下、参考したページです。

Node.JSのSequelize ORM入門
https://qiita.com/markusveeyola/items/64875c9507d5fa32884e

Getting started
https://sequelize.org/v5/manual/getting-started

Node.jsのSequelizeでDBのmigrationを実行する
https://qiita.com/cobot00/items/0bc0da1095e09bcd0d5f

$ sequelize init

Sequelize CLI [Node: 10.17.0, CLI: 5.5.1, ORM: 5.21.5]

Created "config/config.json"
Successfully created models folder at "/home/hiroki/projects/sample_react_booklist/models".
Successfully created migrations folder at "/home/hiroki/projects/sample_react_booklist/migrations".
Successfully created seeders folder at "/home/hiroki/projects/sample_react_booklist/seeders".
# models/index.js も自動生成される

モデルの作成

$ sequelize model:create --name book --underscored --attributes title:string,author:string

Sequelize CLI [Node: 10.17.0, CLI: 5.5.1, ORM: 5.21.5]

New model was created at /home/hiroki/projects/sample_react_booklist/models/book.js .
New migration was created at /home/hiroki/projects/sample_react_booklist/migrations/20200223023505-book.js .

マイグレーション

$ sequelize db:migrate --env development

Sequelize CLI [Node: 10.17.0, CLI: 5.5.1, ORM: 5.21.5]

Loaded configuration file "config/config.json".
Using environment "development".
== 20200223023505-create-book: migrating =======
== 20200223023505-create-book: migrated (0.066s)

Express チュートリアル Part 4: ルートとコントローラ
https://developer.mozilla.org/ja/docs/Learn/Server-side/Express_Nodejs/routes

Migrations
https://sequelize.org/master/manual/migrations.html

Creating the first Seed

$ sequelize seed:generate --name demo-book

Sequelize CLI [Node: 10.17.0, CLI: 5.5.1, ORM: 5.21.5]

seeders folder at "/home/hiroki/projects/sample_react_booklist/seeders" already exists.
New seed was created at /home/hiroki/projects/sample_react_booklist/seeders/20200223045812-demo-book.js .

Running Seeds

$ sequelize db:seed:all
Sequelize CLI [Node: 10.17.0, CLI: 5.5.1, ORM: 5.21.5]

Loaded configuration file "config/config.json".
Using environment "development".
== 20200223045812-demo-books: migrating =======
== 20200223045812-demo-books: migrated (0.028s)