2016-09-13 2 views
0

var 친구의 INDEX 함수에 문제가 있습니다. 처음에는 빈 배열로 설정하여 우정 조인 테이블에서 배열로 개별 사용자 객체를 푸시 할 수 있습니다. 로그인 한 사용자가 누가 우정을 시작했는지에 따라 userID 열 또는 friendID 열의 우정 조인 테이블에 존재할 수 있기 때문입니다.Sequelize : 조인 테이블 문제 및 결과 쿼리

문제는 비동기 특성으로 인해 console.log (친구)를 호출 할 때 데이터베이스 쿼리가 밀리 초 뒤에 있기 때문에 여전히 빈 배열을 로깅합니다. 배열에 현재 사용자가 아닌 사용자 객체가 가득 찼 으면합니다. 본질적으로 백엔드 API에서 JSON을 제공하는 "myfriends"색인 페이지가 될 것입니다. 사실 Json을 지원하려고한다는 사실을 기억하십시오. 따라서 모든 친구 사용자 객체는 하나의 배열로 끝나야합니다.

감사합니다.

var user = require ("../../ models/index"). 사용자; var friendship = require ("../../ models/index") 우정;

var friendshipController = { 
    index: function(req, res) { 
    var friends = []; 
    var request = friendship.findAll({ 
     where: { 
     status: "pending", 
     $and: { 
      $or: [ 
      { 
       userId: req.session.user.id 
      }, 
      { 
       friendId: req.session.user.id 
      } 
      ] 
     } 
     } 
    }).then(function(friendships) { 
     res.json(friendships) 
     var friends = [] 
     friendships.forEach(function(friendship) { 
     if (req.session.user.id === friendship.userId) { 
      user.findById(friendship.friendId).then(function(user) { 
      friends.push(user); 
      }) 
     } else { 
      user.findById(friendship.userId).then(function(user) { 
      friends.push(user); 
      }) 
     } 
     }) 
     console.log(friends); 
    }) 
    }, 
    create: function(req, res) { 
    friendship.create({ 
     userId: req.session.user.id, 
     friendId: 3, 
    }).then(function() { 
     res.redirect("/") 
    }) 
    }, 
    destroy: function(req, res) { 
    friendship.findAll().then(function(f) { 
     f.forEach(function(fn) { 
     fn.destroy() 
     }) 
    }) 
    } 
} 

module.exports = friendshipController; 

답변

0

해결책 : 각 우정, 그 배열 (분명히 sequelize의 기능)의 모든 사용자를 찾기 위해 쿼리를 실행 ... 배열에 로그인 한 사용자의 각 인접한 친구의 ID를 누르면, 다음 응답 그 json 데이터로

index: function(req, res) { 
    var friends = []; 
    var query = friendship.findAll({ 
     where: { 
     status: "pending", 
     $and: { 
      $or: [ 
      { 
       userId: req.session.user.id 
      }, 
      { 
       friendId: req.session.user.id 
      } 
      ] 
     } 
     } 
    }).then(function(friendships) { 
     var friendIds = []; 
     friendships.forEach(function(friendship) { 
      if (req.session.user.id === friendship.userId) { 
      friendIds.push(friendship.friendId); 
      } 
      else { 
      friendIds.push(friendship.userId); 
      } 
     }); 
     user.findAll({ 
      where: { 
      id: friendIds 
      } 
     }).then(function(users) { 
      res.json(users); 
     }) 
    }) 
    }