Javascript SailsJS v0.10多模型关联
我有三种型号。用户、个人资料和评论 配置文件是用户的关联(一对一),注释是配置文件的关联(一对多) 用户模型:Javascript SailsJS v0.10多模型关联,javascript,node.js,sails.js,Javascript,Node.js,Sails.js,我有三种型号。用户、个人资料和评论 配置文件是用户的关联(一对一),注释是配置文件的关联(一对多) 用户模型: attributes: { profile: { model: 'Profile' }, } 配置文件模型: attributes: { comments: { collection: 'profileComment', via: 'profile' } } 评论模式: attributes: { profile: { mod
attributes: {
profile: {
model: 'Profile'
},
}
配置文件模型:
attributes: {
comments: {
collection: 'profileComment',
via: 'profile'
}
}
评论模式:
attributes: {
profile: {
model: 'Profile'
},
}
获取用户配置文件工作正常:
User.findOneById(id)
.populate('profile')
.exec(function (err, user) {
// user.profile
});
但是,我该如何用注释填充配置文件呢?通过在
配置文件上设置用户
属性,您似乎可以回到您想要的位置:
attributes: {
comments: {
collection: 'profileComment',
via: 'profile'
},
user: {
model: 'User'
}
}
然后查询:
Profile.findOne({user: userId})
.populate('user')
.populate('comments')
.exec(function(err, profile) {
// use profile.user and profile.comments
});
但是,请记住,Waterline当前并没有实现真正的一对一关联,因此,如果将配置文件
实例的用户
属性设置为123
,则相应的用户
实例不会自动设置其配置文件
属性。这可能没什么大不了的——您可以随时查找配置文件
并填充用户
,就像上面的示例一样——但这是需要记住的
您的另一个选择是保持事物的原样并进行映射,如中所示