我正在运行最新的数据库适配器(PostgreSQL)的Sails.js测试版本(v0.10.0-rc3),这使我可以通过Waterline ORM实现关联功能。我尝试创建一个基于角色的用户模型,以授权不同访问级别。用户到角色的关联是一对多的。我的模型如下:
api/models/User.js
module.exports = {
attributes: {
firstName: {
type: 'string',
required: true
},
lastName: {
type: 'string',
required: true
},
fullName: function() {
return this.firstName + " " + this.lastName;
},
email: {
type: 'email',
required: true,
unique: true
},
encryptedPassword: {
type: 'string'
},
role: {
model: 'role'
},
groups: {
collection: 'group',
via: 'users'
}
},
toJSON: function() {
var obj = this.toObject();
delete obj.password;
delete obj.confirmation;
delete obj._csrf;
return obj;
},
beforeCreate: function (values, next) {
// Makes sure the password and password confirmation match
if (!values.password || values.password != values.confirmation) {
return next({err: ['Password does not match password confirmation.']});
}
// Encrypts the password/confirmation to be stored in the db
require('bcrypt').hash(values.password, 10, function passwordEncrypted(err, encryptedPassword) {
values.encryptedPassword = encryptedPassword;
next();
});
}
};
api/models/Role.js
module.exports = {
attributes: {
name: {
type: 'string',
required: true,
unique: true
},
users: {
collection: 'user',
via: 'role'
},
permissions: {
collection: 'permission',
via: 'roles',
dominant: true
}
}
};
我知道Waterline目前还不支持Through Associations,但是我仍然应该能够访问与用户关联的角色名称,对吗?例如:user.role.name
。目前我唯一能够检索到角色名称的方法是进行第二个查询以获取角色对象。