일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 서브셋폰트
- 상속
- 캡슐화
- git
- Secret
- GOF
- 추상화
- dfs
- PostgreSQL
- 다형성
- azure
- MariaDB
- 클라우드
- 객체지향
- npm
- Java
- 동적계획법
- AOP
- bfs
- CSS
- netlify
- package
- mock
- process.env
- Solid
- 디자인 패턴
- github
- dotenv
- DP
- 메모이제이션
Archives
- Today
- Total
이것저것 해보기🌼
Sequelize를 사용한 ORM 구현 본문
1. Sequelize 설치
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 결과 확인하기
'BE > Node.js' 카테고리의 다른 글
Sequelize migration 으로 안전하게 데이터베이스 스키마 변경하기 (2) | 2024.09.04 |
---|---|
Node.js + postgreSQL 연동 및 쿼리 실행 (2) | 2024.09.04 |