从Sails.js中的关联模型访问模型的属性

问题描述 投票:4回答:1

我正在使用更新的数据库适配器(对于PostgreSQL)运行Sails.js的beta版本(v0.10.0-rc3),以便通过Waterline ORM获得关联功能。我正在尝试根据不同的访问级别创建基于角色的授权用户模型。用户到角色关联是一对多的。我的模特是:

API /模型/ 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 /模型/ 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我现在能够检索角色名称的唯一方法是对角色对象进行第二次查询。

javascript node.js postgresql sails.js waterline
1个回答
3
投票

为了访问关联的模型,在查询主模型时必须使用populate关联,例如:

User.findOne(1).populate('role').exec(function(err, user) {

    if (err) {throw new Error(err);} 
    console.log(user.role.name);

}

协会文档是here

© www.soinside.com 2019 - 2024. All rights reserved.