我如何在帆上检索一对一的关联.JS控制器以获取列表/索引视图



刚开始使用Sails.js-如何以以下模型来检索一对一的关联?我认为我有一个单一的视图,但是在列出列表方面挣扎。单独使用控制器或更具灵活性似乎可以使用服务,但是在两种情况下语法都是我的绊脚石...我一直在得到 undefined >根本没有任何内容。。

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(如果存在用户ID)

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);
      }
    });
  }

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

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);
    }
  });
}

最新更新