我有 2 个模型,用户和 friend 。在 friend 中我有 2 列( UserId1,UserId2) 我想在 friend 行中找到指定了 UserId1 的行,然后从包含这些行的表中返回包含 Id = UserId2 的用户的表
index: function(req, res, next) {
Friend.find({UserId1 : req.session.User.id}, function foundUsers(err, friends) {
if (err) return next(err);
// pass the array down to the /views/index.ejs page
res.view({
friends: friends
});
});
}
上面的代码返回带有 Friends(UserId1, UserId2) 的表,其中指定了 UserId1,但是如何返回带有 Users 的表(来自模型 User),其中 Id = UserId2 ??
最佳答案
所以,听起来您正在使用 Friend
模型作为表示两个用户之间的友谊的连接表。您当前在代码中的查询获取连接表中的所有记录,其中 UserId1
是您登录用户的 ID,对于每条记录,您希望获得完整的 User
id 与 UserId2
匹配的用户的对象柱子。如果是这种情况,完整的代码可能类似于:
index: function(req, res) {
Friend.find({UserId1 : req.session.User.id})
.exec(function foundUsers(err, friend_records) {
if (err) return res.serverError(err);
// Get an array of all the UserId2 values, using sails.util.pluck,
// which is essentially Lodash's _.pluck
var friend_ids = sails.util.pluck(friend_records, 'id');
// Get the User records for those users. Using an array
// in the criteria makes Waterline do an "in" query
User.find({id: friend_ids}).exec(function(err, friends) {
// pass the array down to the /views/index.ejs page
res.view({
friends: friends
});
});
});
}
一些注意事项:
- 您几乎不应该使用
next
在您的 Controller 代码中,特别是对于错误处理。如果出现错误,请使用响应进行处理。保存next
对于 policies除非您真的、真的打算让另一个 Controller 为您处理响应。 - Sails v0.10(目前处于测试阶段)包括 support for associations ,它将为您处理连接表。
关于javascript - 如何在 Sails.js 中从多个模型返回 JavaScript 中的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22617871/