Szybka pomoc

Ściągawka z Sequelize ORM

Szybki przewodnik po Sequelize: bazujący na obietnicach ORM dla Node.js obsługujący Postgres, MySQL, SQLite, definicje modeli i zapytania.

· Opublikowano

Sequelize to oparty na obietnicach ORM dla Node.js obsługujący Postgres, MySQL, MariaDB, SQLite oraz SQL Server.

Połączenie i definicja modelu

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 }
  }
});

// Synchronizacja schematu bazy danych
await sequelize.sync();

Operacje CRUD

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

// Odczyt (Read)
const users = await User.findAll({
  where: { name: 'Alice' },
  order: [['createdAt', 'DESC']],
  limit: 10
});

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

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

Relacje między modelami (Associations)

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

// Eager loading z użyciem include
const userWithPosts = await User.findOne({
  where: { id: 1 },
  include: [Post]
});

Źródła i dokumentacja

Powiązane tematy