0
0

More than 1 year has passed since last update.

Webの勉強はじめてみた その35 〜Sequelizeを使った実装〜

Posted at

N予備校「プログラミング入門Webアプリ」を受講しています。
今回は第4章18,19節です。

UUID

任意のIDを作る。全世界で同じ値を持つことがない一意な識別子。

データベースのデータ型として、UUIDが用意されている。

Node.jsで使う場合はライブラリをインストールする。

yarn add uuid@3.3.2

データモデルの作成

models/schedule.js
'use strict';
const {sequelize, DataTypes} = require('./sequelize-loader');

const Schedule = sequelize.define(
  'schedules',
  {
    scheduleId: {
      type: DataTypes.UUID,
      primaryKey: true,
      allowNull: false
    },
    scheduleName: {
      type: DataTypes.STRING,
      allowNull: false
    },
    memo: {
      type: DataTypes.TEXT,
      allowNull: false
    },
    createdBy: {
      type: DataTypes.INTEGER,
      allowNull: false
    },
    updatedAt: {
      type: DataTypes.DATE,
      allowNull: false
    }
  },
  {
    freezeTableName: true,
    timestamps: false,
    indexes: [
      {
        fields: ['createdBy']
      }
    ]
  }
);

module.exports = Schedule;

indexes
CREATE INDEXと同じ。あらかじめインデックスを作れる。

データテーブル作成

app.js
// Read DB Model
const User = require('./models/user');
const Schedule = require('./models/schedule');
const Availability = require('./models/availability');
const Candidate = require('./models/candidate');
const Comment = require('./models/comment');
User.sync().then(() => {
  Schedule.belongsTo(User, {foreignKey: 'createdBy'});
  Schedule.sync();
  Comment.belongsTo(User, {foreingKey: 'userId'});
  Comment.sync();
  Availability.belongsTo(User, {foreignKey: 'userId'});
  Candidate.sync().then(() =>{
    Availability.belongsTo(Candidate, {foreignKey: 'candidateId'});
    Availability.sync();
  })
})

sync
データモデルに合わせて、データテーブルを作成する。
データモデルを使ってエンティティ同士の関係を定義することで、後で自動的に RDB上でテーブルの結合をしてデータを取得できる。

Schedule.blongsTo(User, {foreignKey:'createdBy'})
ScheduleUserに所属しているという意味。
SchedulecreatedByUserの主キーを結合する。

JOIN操作を前もって定義してるという認識。

JOIN

Schedule.findOne({
  include: [
    {
      model: User,
      attributes: ['userId', 'userName']
    }
  ],
  where: {
    scheduleId: req.params.scheduleId
  },
  order: [['updatedAt', 'DESC']]
})

findOne
データモデルに対応するデータを1件取得する。

include
JOIN操作

model
JOINするデータモデル

attributes
取得してくる値

bulkCreate

配列を渡して、複数のデータを登録する。

function createCandidatesAndRedirect(candidateNames, scheduleId, res){
  const candidates = candidateNames.map((c) => {
    return {
      candidateName: c,
      scheduleId: scheduleId
    };
  });
  // candidateテーブルに 複数データを Insert
  Candidate.bulkCreate(candidates).then(() => {
    // 作成したスケジュールIDへリダイレクト
    res.redirect(`/schedules/${scheduleId}`);
  });
}

まとめ

以前はVB.NETにしろPHPにしろ、SQLを直接プログラムに書いてたクチなので、こういうSequelizeを使っての実装は、SQLが見えない分ちょっとわかりにくい印象。
belongsToはちょっと違うと思うけどviewを前もって定義するようなイメージでいます。

0
0
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
0
0