javascript - 如何在 Sails.js 中从多个模型返回 JavaScript 中的表

标签 javascript sails.js waterline

我有 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/

相关文章:

javascript - 请求正文中的 Facebook Messenger API 内容不完整

database - sails .js : Is Waterline ORM safe without foreign key constraints?

javascript - Sails.JS - 获取数据库中对象/行的数量

javascript - Typescript reducer 问题

javascript - 使用 React 和 es6 清理电子邮件输入

javascript - 在切换模式下根据不同标签渲染数组中的导航列表

node.js - Sails.js Redis 如何流式传输数据?

javascript - 使用 JavaScript 脚本加载外部 HTML(通过 WordPress 中的嵌入代码)

angularjs - 如何使用 MEAN 和sails.js 开始一个新项目

javascript - 如何在 Sails.js 中进行原子 Controller 操作