Sequelize入門
SequelizeというORMについて知識の整理のため、記録を残そうと思う。Databaseはmysqlを使用する。
今回は、
1. database作成
2. table作成
3. insert, update, delete
という基本的なことの整理をしたい
1. databaseの作り方
databaseを作成するのは、sequelizeではなく、sequelize-cli
を利用するので、両方インストールする。
npm i -D sequelize-cli sequelize mysql2
以下のファイルを作成する。
config.json
{ "username": "root", "password": "****", "database": "sequelize", "host": "127.0.0.1", "dialect": "mysql" }
次のコマンドを叩く
npx sequelize db:create --config config.json
$ npx sequelize db:create --config config.json Sequelize CLI [Node: 8.12.0, CLI: 5.5.0, ORM: 5.10.0] Loaded configuration file "config.json". Database sequelize created.
注意として、npxに続くのがsequelize-cliではなく、sequelizeであること。
これでsequelizeというdatabaseが作成される。
2. tableの作成
main.jsを作成する。
main.js
const { database, username, password, host, dialect } = require("./config"); const Sequelize = require("sequelize"); const { Model } = Sequelize; // database接続 const sequelize = new Sequelize(database, username, password, { host, dialect }); // Model定義 class Project extends Model {} Project.init( { title: Sequelize.STRING, description: Sequelize.TEXT }, { sequelize, modelName: "project" } ); (async () => { // Projectテーブル作成 await Project.sync({ force: true }) })()
node main.js
と実行すると
大文字、小文字のsequelizeが出てくるので混乱するかもしれないが、
大文字がSequlizeライブラリとしての情報を、小文字がdatabase接続した情報をもっていると理解すればよいのであろう。
Project.initでORMのMを定義している。
この場合、
- String型のtitle
- Text型のdescription
をもつテーブルを作成しようとしてる。
さらにORMによって自動的に、id(PK)やcreateAt, updateAtも作成される。 createAd, updateAtをつけたくない場合は、timestampsプロパティを利用して、
{sequelize, modelName: 'project', timestamps: false}
と記述すればよい。
Project.sync()
でtable作成しており、{force: true}を与えることでdrop & createとなる。
insert, update, deleteの実行
以下main.js
の続きとして書いていきます。
1レコードの場合
(async () => { // instanceを作成する。ここではまだinsertされていない。 const project = Project.build({ title: "my awesome project", description: "woot woot. this will make me a rich man" }); // insert const created = await project.save(); // (1) // update const updated = await project.update({ // (2) title: 'update title' }); // delete const deleted = await project.destroy(); // (3) })()
帰ってきた値のtoJSON()メソッドを適用すると以下の結果を受け取れる。
(1) insertされたレコードの情報を取得できる(created.toJSON())
{ id: 1, title: 'my awesome project', description: 'woot woot. this will make me a rich man', updatedAt: 2019-07-14T13:44:17.720Z, createdAt: 2019-07-14T13:44:17.720Z }
(2) updateされたレコードの情報を取得できる(updated.toJSON())
{ id: 1, title: 'update title', description: 'woot woot. this will make me a rich man', updatedAt: 2019-07-14T13:44:17.751Z, createdAt: 2019-07-14T13:44:17.720Z }
(3) deleteされたレコードの情報を取得できる(deleted.toJSON())
{ id: 1, title: 'update title', description: 'woot woot. this will make me a rich man', updatedAt: 2019-07-14T13:44:17.751Z, createdAt: 2019-07-14T13:44:17.720Z }
複数レコードの場合
update, destoryは複数レコードに対応できるが、insertの場合、
bulkCreate
というメソッドを利用する。
main.js
(async () => { const results = await Project.bulkCreate([ { title: "programming", description: "executing" }, { title: "reading", description: "executing" }, { title: "programming", description: "finished" } ]); console.log(results.map(d => d.toJSON())) })()
[ { id: 1, title: 'programming', description: 'executing', createdAt: 2019-07-14T13:53:49.986Z, updatedAt: 2019-07-14T13:53:49.986Z }, { id: 2, title: 'reading', description: 'executing', createdAt: 2019-07-14T13:53:49.986Z, updatedAt: 2019-07-14T13:53:49.986Z }, { id: 3, title: 'programming', description: 'finished', createdAt: 2019-07-14T13:53:49.986Z, updatedAt: 2019-07-14T13:53:49.986Z } ]
さいごに
次は、whereやgroup by句やテーブルのjoinなどのselectに関するものをまとめようと思う。 joinこそがORMで一番理解が難しいところだと思ってる。