[英]Sequelize: Issue with join table and querying for results
在var朋友上,INDEX函数中存在问题。 我想将其最初设置为一个空数组,以便可以将用户的友谊联接表中的各个用户对象推送到所述数组。 这是因为已登录的用户可能存在于友谊连接表的userID列或friendID列下,具体取决于谁发起了友谊。
问题是由于异步性质,当我调用console.log(friends)时,数据库查询落后了毫秒,因此它仍在记录一个空数组。 我希望数组中充满*不是当前用户的用户对象,从本质上讲,这将是一个“ myfriends”索引页面,该页面通过后端API提供JSON。 请记住,我正在尝试为Json服务,因此所有朋友用户对象都必须以单个数组结尾。
谢谢!
var user = require(“ ../../ models / index”)。user; var friendly = require(“ ../../ models / index”)。friendship;
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;
解决方案:对于每个友谊,将登录用户的每个相邻朋友的ID推送到一个数组...在运行查询以查找该数组中的所有用户(显然是sequelize的功能)之后,然后使用该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);
})
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.