我使用的是Sails.js 0.10.x.我将与"Create new record while associating w/ another new record (REST)"一起记录的功能与多租户系统结合起来。所有模型都有一个related_account作为主键的一部分。我需要找到一种防弹方式,让它始终充满当前用户相关的帐户。
在父子关系中,通过覆盖蓝图并在创建记录之前简单地设置related_account属性,可以很容易地填充父级的related_account。但是当javascript对象传递给Model.create(parent_and_children)时,这意味着我必须遍历所有子节点并在创建之前手动设置related_account。这项工作繁琐且容易出错,因为在很多情况下我需要这样做。此外,这可能是导致严重缺陷的原因,因为我们在团队中工作,有人可能忘记添加它。在某些情况下,可能会使用标准蓝图,在其他情况下,可以手动执行操作。
必须有一种比手动设置更好的方式。任何想法都值得赞赏。
顺便说一句:related_account的值在请求变量" user"中可用。
答案 0 :(得分:1)
也许这会有所帮助。我正在做同样的事情,我需要每个记录的登录用户的companyId(在session.user.company.id中找到)。所以这是我的解决方案。这是一个策略,检查模型是否有任何关联,然后循环通过在req.body对象中添加companyId的那些关联。
module.exports = function(req, res, next) {
req.options.where = _.assign({companyId : req.session.user.company.id}, req.options.where);
var attachCompanyIdToBody = function(){
if(_.isArray(req.body)){
} else if (_.isObject(req.body)){
req.body.companyId = req.session.user.company.id;
attachCompanyIdToAssociations();
}
};
var attachCompanyIdToAssociations = function(){
// Get assocations with current model
var Model = actionUtil.parseModel(req);
if(Model.associations){
_.forEach(Model.associations, function(item,index,object){
// if has company attached, remove company
if(req.body[item.alias] && item.alias.toLowerCase() !== 'company'){
if(_.isArray(req.body[item.alias])){
// ToDo if assocation is a collection then loop through collection adding companyId
} else if(_.isObject(req.body[item.alias])){
// if assocation is object then add companyId to object
req.body[item.alias].companyId = req.session.user.company.id;
}
}
});
}
};
if(req.body){
attachCompanyIdToBody();
}
return next();
};