Sequelize EagerLoadingError: association 별칭 미설정 에러

Creating the dots·2021년 11월 30일
0

project-3-ShallWeHealth

목록 보기
12/26

어떤 에러?

  • 하나의 테이블이 여러개의 fk를 갖고 있는 경우 include로 join할때 특정 fk를 선택해야하므로 as를 써주어야합니다.

에러 메시지

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

에러 핸들링 방법

  • model 폴더 내 파일의 associate 부분을 확인해야합니다.
  • 두 파일에 (연결되어있으므로 두개의 파일을 모두 확인해야합니다) 설정된 association의 옵션객체에 foreignKey, as가 설정되어있는지 확인합니다.
  • 옵션객체에 정의한 as를 나중에 join할때 사용합니다.
 const { count, rows } = await Post.findAndCountAll({
        include: [
          { model: User, as: "guests", attributes: ["nickname"] }, // as가 여기서 사용됩니다.
          { model: User, as: "hosts", attributes: ["nickname"] },
        ],
        offset,
        limit,
        order: [["createdAt", "ASC"]],
      });
      return res.status(200).json({ data: rows, count });
profile
어제보다 나은 오늘을 만드는 중

0개의 댓글