강의

멘토링

커뮤니티

Cộng đồng Hỏi & Đáp của Inflearn

Hình ảnh hồ sơ của nan84203857
nan84203857

câu hỏi đã được viết

[Gia hạn] Tạo NodeBird SNS bằng React

질문있습니다.

Viết

·

622

0

안녕하세요 제로초님

팔로워 팔로잉 기능을 유저와 포스트 관계로 응용하려 합니다.

그래서 User모델에 

db.User.belongsToMany(db.Post, { through: 'Follow'as: 'Followings'foreignKey: 'FollowerId' });

Post모델에

  db.Post.belongsToMany(db.User, { through: 'Follow'as: 'Followers'foreignKey: 'FollowingId' });

이런식으로 해주고 

LOAD_MY_INFO_REQUEST,액션으로인해

router.get('/'async (reqresnext=> { // GET /user
  try {
    if (req.user) {
      const fullUserWithoutPassword = await User.findOne({
        where: { id: req.user.id },
        attributes: {
          exclude: ['password']
        },
        include: [ 
          {
          model: Post,
          attributes: ['id'],
        },
        {
          model: User,
          as: 'Followers',
          attributes: ['id'],
        }, 
        {
          model: Post,
          as: 'Followings',
          attributes: ['id'],
        }
      ]
      })
      // console.log("fullUserWithoutPassword::::::::::::",JSON.stringify(fullUserWithoutPassword),"enddddddddddddd");
      res.status(200).json(fullUserWithoutPassword);
    } else {
      res.status(200).json(null);
    }
  } catch (error) {
    console.error(error);
   next(error);
  }
});

라우터가 실행되면 백엔드에서 

EagerLoadingError [SequelizeEagerLoadingError]: User is not associated to User!

유저와 유저가 연결되어 있지 않다고 뜹니다. 그래서  

 {
          model: User,
          as: 'Followings',
          attributes: ['id'],
        }, 
        {
          model: Post,
          as: 'Followers',
          attributes: ['id'],
       }

이런식으로 바꿔줘도 오류는 똑같습니당..

뭐가 잘못된걸까요...

밑에는 데이터베이스 형태입니다.

Next.jsreduxnodejsreactexpress

Câu trả lời 6

0

nan84203857님의 프로필 이미지
nan84203857
Người đặt câu hỏi

감사합니다!!

0

zerocho님의 프로필 이미지
zerocho
Người chia sẻ kiến thức

db.user belongstomany db.post as followings를 하셨으니

user 입장에서는 post가 followings밖에 없습니다.

post입장에서는 users가 followers인 것이고요.

그리고 포린키는 반대라서 followingid에 postid가 들어갑니다.

0

nan84203857님의 프로필 이미지
nan84203857
Người đặt câu hỏi

질문1.

db.Post.belongsToMany(db.User, { through: 'Follow'as: 'Followers'foreignKey: 'FollowingId' });

이렇게 되어있으면 post모델이 Follwers가 되고 foreginkey가 FollwingId가 되는것인가요??....

질문2.

만약 그렇다면 

router.get('/'async (reqresnext=> { // GET /user
  try {
    if (req.user) {
      const fullUserWithoutPassword = await User.findOne({
        where: { id: req.user.id },
        attributes: {
          exclude: ['password']
        },
        include: [ 
          {
          model: Post,
          attributes: ['id'],
        },
        {
          model: Post,
          as: 'Followings',
          attributes: ['id'],
        }, 
        // {
        //   model: Post,
        //   as: 'Followers',
        //   attributes: ['id'],
        // }
      ]
      })
      // console.log("fullUserWithoutPassword::::::::::::",JSON.stringify(fullUserWithoutPassword),"enddddddddddddd");
      res.status(200).json(fullUserWithoutPassword);
    } else {
      res.status(200).json(null);
    }
  } catch (error) {
    console.error(error);
   next(error);
  }
});

위의 라우터에서 Post에서 as를 Followings를 해야만 가져올 수 있더라구요. Follwers를넣으면 오류가나더라구욥..

위의 라우터는 왜 post as Follwers가 안먹히는 걸까요?.. 헷갈리네요 ㅜ

0

zerocho님의 프로필 이미지
zerocho
Người chia sẻ kiến thức

User랑 Post이름을 팔로워팔로잉으로 하니까 엄청 헷갈리네요.

Post모델이 Followers고 foreignKey를 followingId로 하신 것 아닌가요?

db.Post.belongsToMany(db.User, { through: 'Follow'as: 'Followers'foreignKey: 'FollowingId' });

0

nan84203857님의 프로필 이미지
nan84203857
Người đặt câu hỏi

감사합니다.  제가 디비 이해가 부족해서 더 여쭤보겠습니다...ㅜ

 db.User.belongsToMany(db.Post, { through: 'Follow'as: 'Followings'foreignKey: 'FollowerId' });
db.Post.belongsToMany(db.User, { through: 'Follow'as: 'Followers'foreignKey: 'FollowingId' });

위에처럼 post모델의  이름은 Followings이고 foreignKey는 FollwerId이고

User모델은 Follwers 이고 foriegnKey는 FollowingId이잖아요? 

그런데 팔로우하는 라우터에서 이렇게 정해줬을 시

router.patch('/:PostId/follow'isLoggedInasync (reqresnext=> { // PATCH /user/1/follow
  try {
 
    const post = await Post.findOne({ where: { id: req.params.PostId }});
    if (!post) {
      res.status(403).send('없는 사람을 팔로우하려고 하시네요?');
    }
    await post.addFollowers(req.user.id);
    res.status(200).json({ PostId: parseInt(req.params.PostId10) });
  } catch (error) {
    console.error(error);
    next(error);
  }
});

팔로우를 하면  (참고로 req.user.id)는 1이고 req.params.PostId가 2입니다.)

데이터베이스에 Follwerid가 1 FollowingId가 2로 나옵니다.

저는 당연히 Post모델 즉 Followings의 foreignKey가 FollwerId이기 때문에 FollwerId에 2가 들어갈 줄 알았는데. 반대가 되네요?? post모델의 forignKey가 FollwerId인데 왜 데이터베이스에는 FollowingId에 2가 들어가는건지 궁금합니다..

0

zerocho님의 프로필 이미지
zerocho
Người chia sẻ kiến thức

include model User가 아니라 Post겠죠. user와 user의 관계는 더이상 없으니까요.

Hình ảnh hồ sơ của nan84203857
nan84203857

câu hỏi đã được viết

Đặt câu hỏi