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;