[英]How do I retrieve a one-to-one association in a sails.js controller for list/index views?
刚开始使用sails.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;
},
}
};
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;
}
}
};
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.