이것저것 해보기🌼

Sequelize를 사용한 ORM 구현 본문

BE/Node.js

Sequelize를 사용한 ORM 구현

realtree 2024. 9. 4. 18:47

1. Sequelize 설치

https://sequelize.org/

 

Sequelize

Sequelize is a modern TypeScript and Node.js ORM for Oracle, Postgres, MySQL, MariaDB, SQLite and SQL Server, and more. Featuring solid transaction support, relations, eager and lazy loading, read replication and more.

sequelize.org

 

 

2. 테이블 생성, 데이터 추가, Association 설정

- 아래 예시는 User 테이블에 CityId 가 City 테이블의 forein key 가 되는 예시이다.

import { DataTypes, Sequelize } from 'sequelize'

async function main() {
  const sequelize = new Sequelize({
    database: '[database]',
    username: '[user]',
    password: '[password]',
    dialect: 'postgres',
    host: 'localhost',
  })

  const User = sequelize.define(
    'user',
    {
      id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true,
      },
      name: {
        type: DataTypes.STRING,
        allowNull: false,
      },
      age: {
        type: DataTypes.INTEGER,
        allowNull: false,
      },
    },
    {
      timestamps: false,
    },
  )

  const City = sequelize.define(
    'city',
    {
      id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true,
      },
      name: {
        type: DataTypes.STRING,
        allowNull: false,
      },
    },
    {
      timestamps: false,
    },
  )

  User.belongsTo(City)

  await sequelize.sync({
    force: true,
  })

  const newCity = await City.build({
    name: 'Seoul',
  }).save()

  const newUser = User.build({
    name: 'seohee',
    age: 20,
    cityId: newCity.id,
  })
  await newUser.save()

  await sequelize.authenticate()
  await sequelize.close()
}

main()

 

3. 실행 후 DB 결과 확인하기