인프런 영문 브랜드 로고
인프런 영문 브랜드 로고

인프런 커뮤니티 질문&답변

정중한 전어님의 프로필 이미지
정중한 전어

작성한 질문수

React로 NodeBird SNS 만들기

LIKE 기능 구현 중 문제점 생겨 질문 드립니다

해결된 질문

작성

·

248

0

안녕하세요! LIKE 기능 구현 중 문제점 생겨 질문 드립니다. 강의(6-14. 게시글 좋아요, 좋아요 취소) 따라가며 진행하고 있습니다.

백엔드 router에서 LIKER를 불러오지 않아 failure가 떠서 posts.js, hashtag.js, user.js의 게시글을 불러오는 router에 LIKER를 불러오는 것 까지 따라하였는데요.

GET /api/posts 500 17.049 ms - 2323

SequelizeEagerLoadingError: User is associated to Post multiple times. To identify the correct association, you must use the 'as' keyword to specify the alias of the association you want to include.

수정을 하자 해당 에러가 뜨면서 갑자기 posts가 불러와지지 않습니다.

posts.js 라우터 파일의 코드는 이렇게 작성했습니다.

const express = require('express');
const db = require('../models');
const router = express.Router();

router.get('/', async(req, res, next) => { // GET /api/posts
try{
const posts = await db.Post.findAll({
include: [{
model: db.User,
attributes: ['id', 'nickname']
},{
model: db.Image
}, {
model: db.User,
through: 'Like',
as: 'Likers',
attributes: ['id']
}],
order: [['createdAt', 'DESC' ], ['updatedAt', 'ASC']], //DESC 내림차순, ASD 오름차순
});
res.json(posts);
}catch(e){
console.error(e);
next(e);
}
});


module.exports = router;

아래는 models의 post.js 파일입니다

module.exports = (sequelize, DataTypes) => {
const Post = sequelize.define('Post', {
content: {
type: DataTypes.TEXT, // 매우 긴 글
allowNull: false,
}
}, {
charset: 'utf8mb4', // 한글 + 이모티콘
collate: 'utf8mb4_general_ci', // 한글이 저장
});
Post.associate = (db) => {
db.Post.belongsTo(db.User);
db.Post.hasMany(db.Comment);
db.Post.hasMany(db.Image);
db.Post.belongsTo(db.Post, {as: 'Retweet'});
db.Post.belongsToMany(db.Hashtag, {through: 'PostHashtag'});
db.Post.belongsToMany(db.User, { through: 'Like', as: "Liker"});
};

return Post;
}

왜 저런 에러가 뜨는지 갈피가 잡히지 않아 질문드려요 ㅠㅠ 도움 주시면 감사하겠습니다!

답변 1

0

헉 제가 model 쪽에 오타를 냈었네요 답변 달아주지 않으셔도 괜찮습니다!!!!

정중한 전어님의 프로필 이미지
정중한 전어

작성한 질문수

질문하기