我是SequelizeJS的新手。我的问题是如何在json中存储多个模型的结果。我已经调用了两个模型Users
和Friends
,我希望在JSON中获得两个模型的结果。我试图返回return res.json({"OnlineUsers": onlineUsers, "onlineFriends": onlineFriends});
两个结果只有一个JSON,但没有得到结果。
以下是我的控制器的样子
'use strict';
var models = require('../models');
var Sequelize = require('sequelize');
exports.search = function (req, res) {
if (req.body.searchType === "OnlineUsers") {
var user = new models.Users();
var onlineUsers = user.onlineUsers();
var attributes = {"id": '', "username": "", "role": ""};
var onlineUsers = models.Users.findAll({
attributes: Object.keys(attributes).concat([
[Sequelize.literal("IF(Users.lastSeen < DATE_SUB(NOW(), INTERVAL 15 MINUTE), 0, 1)"), 'isSeen'],
]),
}).then(onlineUsers => {
return onlineUsers;
});;
var onlineFriends = models.Friends.findAll({
attributes: Object.keys(attributes).concat([
[Sequelize.literal("IF(Users.lastSeen < DATE_SUB(NOW(), INTERVAL 15 MINUTE), 0, 1)"), 'isSeen'],
]),
}).then(onlineFriends => {
return onlineFriends;
});
return res.json({"OnlineUsers": onlineUsers, "onlineUsers": onlineFriends});
}
//return res.json({searchResult: "test"});
};
任何人都可以帮助我或指导我实现这一目标吗?
答案 0 :(得分:1)
您必须嵌套查询,请记住node.js是异步的,因此在执行第一个查询之后执行第二个查询,然后返回包含两个对象的响应。像这样:
exports.search = function (req, res) {
if (req.body.searchType === "OnlineUsers") {
var user = new models.Users();
var onlineUsers = user.onlineUsers();
var attributes = {"id": '', "username": "", "role": ""};
models.Users.findAll({
attributes: Object.keys(attributes).concat([
[Sequelize.literal("IF(Users.lastSeen < DATE_SUB(NOW(), INTERVAL 15 MINUTE), 0, 1)"), 'isSeen'],
]),
}).then(onlineUsers => {
return models.Friends.findAll({
attributes: Object.keys(attributes).concat([
[Sequelize.literal("IF(Users.lastSeen < DATE_SUB(NOW(), INTERVAL 15 MINUTE), 0, 1)"), 'isSeen'],
]),
}).then(onlineFriends => {
res.json({"OnlineUsers": onlineUsers, "onlineFriends": onlineFriends});
});
});;
}
};