Node.js

[Node.js] sequelize 관계 정의 (associations)

오늘보다 더 나은 내일을 위해 2022. 4. 6. 13:59

1:1관계 (One-To-One)

- hasOne, belongsTo 사용

db.User.hasOne(db.Info, {foreignKey: 'UserOd', sourceKey: 'id'});

db.Info.belongsTo(db.User, {foreignKey: 'UserId', targetKey: 'id'});

 

 

 

1:N관계 (One-To-Many)

- hasMany, belongsTo 사용

db.User.hasMany(db.Comment, {foreignKey: 'commenter', sourceKey: 'id'});

db.Comment.belongsTo(db.USer, {foreignKey: 'commenter', targetKey: 'id'});

 

 

N:M관계 (Many-To-Many) 

- belongsToMany 사용

db.Post.belongsToMany(db.Hashtag, {through: 'PostHashtag'});

db.Hashtag.belongsToMany(db.Post, {through: 'PostHashtag'});

 

N:M 관계의 경우 새로운 모델이 생성된다

through 속성에 새로운 모델의 이름을 적어주면 된다.

 

 

 

 

 

 

https://inpa.tistory.com/entry/ORM-%F0%9F%93%9A-%EC%8B%9C%ED%80%84%EB%9D%BC%EC%9D%B4%EC%A6%88-%EB%AA%A8%EB%8D%B8-%EC%A0%95%EC%9D%98%ED%95%98%EA%B8%B0?category=903202

 

[ORM] 📚 시퀄라이즈 - 모델(테이블) 정의하기

Mysql 테이블 생성 구문 create schema `nodejs` default character set utf8; use nodejs; drop table if exists comments; drop table if exists users; create table nodejs.users ( id int not null primary..

inpa.tistory.com

이 글을 보고 정리한 내용입니다