DB 연결 구성을 시퀄라이즈를 이용하여 설계하는데
어제, 오늘 트러블 슈팅으로 늦어졌다
원인은 공식 문서를 정독하지 않아서이다..
연결 구성(association) 방법에는 2가지가 있다.
2번은 시간이 오래 걸려 1번 방식을 시도했다.
models/index.js에 관계 구성을 작성하고,
//1:N cases
user.hasMany(comment, { foreignKey: 'userId', sourceKey: 'id' });
comment.belongsTo(user, { foreignKey: 'userId', targetKey: 'id' });
user.hasMany(content, { foreignKey: 'userId', sourceKey: 'id' });
content.belongsTo(user, { foreignKey: 'userId', targetKey: 'id' });
content.hasMany(comment, { foreignKey: 'contentId', sourceKey: 'id' });
comment.belongsTo(content, { foreignKey: 'contentId', targetKey: 'id' });
categorie.hasMany(content, { foreignKey: 'categoryId', sourceKey: 'id' });
content.belongsTo(categorie, { foreignKey: 'categoryId', targetKey: 'id' });
content.hasMany(image, { foreignKey: 'contentId', sourceKey: 'id' });
image.belongsTo(content, { foreignKey: 'contentId', targetKey: 'id' });
// N:M cases
user.belongsToMany(label, { through: 'user_label', foreignKey: 'userId' });
label.belongsToMany(user, { through: 'user_label', foreignKey: 'labelId' });
user_label.belongsTo(user, { foreignKey: 'userId' });
user_label.belongsTo(label, { foreignKey: 'labelId' });
서버를 구동하는 js 파일 상단에 아래의 코드를 적어주고,
const sequelize = require('./models').sequelize;
아래의 코드도 적어주었다.
sequelize.sync()
계속 혼자 끙끙 앓다가 스택오버플로에 검색해서 도움을 받았다.
const app = express();
sequelize.sync();
app이 시작되는 지점 밑에 sequlize.sync()를 작성해야 정상 작동한다.
app의 시작점 위에 작성했기 때문에, 코드 실행 순서의 문제로 작동이 안됐던 것이다.