繁体   English   中英

如何在sails.js控制器中检索列表/索引视图的一对一关联?

[英]How do I retrieve a one-to-one association in a sails.js controller for list/index views?

刚开始使用sails.js-如何以以下模型为例检索一对一关联? 我认为我已经处理了单个视图,但是在列表视图中苦苦挣扎。 似乎可以单独使用控制器,也可以为了获得更大的灵活性而使用服务,但是这两种情况下的语法都是我的绊脚石……我一直处于 未定义状态什么都没有 ...

User.js

module.exports = {
  attributes: {
    displayName: {
      type: 'string',
      unique: true
    },
    username: {
      type: 'string',
      required: true,
      unique: true
    },
    email: {
      type: 'email',
      unique: true
    },
    password: {
      type: 'string',
      minLength: 8
    },
    profile: function(callback) {
      Person
        .findByUserId(this.id)
        .done(function(err, profile) {
          callback(profile);
        });
    },
    // Override toJSON instance method to remove password value
    toJSON: function() {
      var obj = this.toObject();
      delete obj.password;
      delete obj.confirmation;
      delete obj.plaintextPassword;
      delete obj.sessionId;
      delete obj._csrf;
      return obj;
    },
  }
};

Person.js(如果存在userId,则用作配置文件)

module.exports = {

  attributes: {
    userId: {
      type: 'string'
    },
    firstName: {
      type: 'string'
    },
    lastName: {
      type: 'string'
    },
    // Override toJSON instance method to remove password value
    toJSON: function() {
      var obj = this.toObject();
      delete obj.sessionId;
      delete obj._csrf;
      return obj;
    }
  }
};

UserController.js

  show: function(req, res) {
    var userId = req.param('id');
    async.parallel({
      profile: function(callback) {
        UserService.getProfileForUser(userId, callback);
      },
      user: function(callback) {
        UserService.getUser(userId, callback);
      }
    },
    function(error, data) {
      if (error) {
        res.send(error.status ? error.status : 500, error.message ? error.message : error);
      } else {
        data.layout = req.isAjax ? "layout_ajax" : "layout";
        data.userId = userId;
        res.view(data);
      }
    });
  }

对于两个模型之间的一对一关联,您无需编写自己的自定义函数。 它内置在Sails中。 有关更多详细信息,请参见Sails文档

User.js

module.exports = {
  ...,
  profile: {
    model: person;
  },
  ...
}

Person.js

module.exports = {
  ...,
  user: {
    model: 'user'
  },
  ...
}

UserController.js

show: function(req, res) {
  var userId = req.param('id');
  User.findOne(userId).populate('profile').exec(function (err, user) {
    if (error) {
      res.send(error.status ? error.status : 500, error.message ? error.message : error);
    } else {
      var profile = user.profile;
      var data = { user: user, profile: profile };
      data.layout = req.isAjax ? "layout_ajax" : "layout";
      data.userId = userId;
      res.view(data);
    }
  });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM