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

刚开始使用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(用作configuration文件,如果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); } }); }