[英]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.