クイックリファレンス

Sequelize ORM チートシート

Sequelize のクイックリファレンス:Postgres、MySQL、SQLite 向け Promise ベースの Node.js ORM、モデル定義、クエリ、リレーションの解説。

· 公開日

Sequelize は、Postgres、MySQL、MariaDB、SQLite、Microsoft SQL Server をサポートする Promise ベースの Node.js 向け ORM です。

接続とモデル定義

const { Sequelize, DataTypes } = require('sequelize');

const sequelize = new Sequelize('postgres://user:pass@localhost:5432/mydb');

const User = sequelize.define('User', {
  name: {
    type: DataTypes.STRING,
    allowNull: false
  },
  email: {
    type: DataTypes.STRING,
    unique: true,
    validate: { isEmail: true }
  }
});

// データベーススキーマの同期
await sequelize.sync();

CRUD 操作

// 作成 (Create)
const user = await User.create({ name: 'Alice', email: '[email protected]' });

// 読み取り・検索 (Read)
const users = await User.findAll({
  where: { name: 'Alice' },
  order: [['createdAt', 'DESC']],
  limit: 10
});

// 更新 (Update)
await User.update({ name: 'Bob' }, { where: { id: 1 } });

// 削除 (Delete)
await User.destroy({ where: { id: 1 } });

モデルのリレーション・関連付け

User.hasMany(Post);
Post.belongsTo(User);

// include によるイーガーローディング
const userWithPosts = await User.findOne({
  where: { id: 1 },
  include: [Post]
});

参考リンク

関連テーマ