dan
dan

Reputation: 2957

How do you access the Roles model from a custom user model in loopback using mysql datasource

Windows 7 x64 loopback-cli 3.10

I have seen some other related questions but they have not solved my problem I have read the docs about how to gain access to an unrelated model within another model but in my case it will not work

I want to be able to access the role model inside the user model as in

let models = require('../../server/model-config.json');
let app = require('../../server/server.js');

module.exports = function (user) {

  let Role = app.models.Role;
  let RoleMapping = app.models.RoleMapping;

}

The above results in both being undefined.

As a boot script this works but I would prefer it all to be in the user model.

module.exports = function (app) {
  var User = app.models.user;
  var Role = app.models.Role;
  var RoleMapping = app.models.RoleMapping;


  RoleMapping.belongsTo(User);
  User.hasMany(RoleMapping, {foreignKey: 'principalId'});
  Role.hasMany(User, {through: RoleMapping, foreignKey: 'roleId'});
};

My relations are defined as

user.json

  "relations": {
    "roles": {
      "type": "hasMany",
      "model": "Role",
      "foreignKey": "principalId",
      "through": "RoleMapping"
    }
  }

Upvotes: 0

Views: 218

Answers (1)

Nimatullah Razmjo
Nimatullah Razmjo

Reputation: 1961

I am not sure exactly what you mean, but you can access once all the model is loaded. with following

let models = require('../../server/model-config.json');
let app = require('../../server/server.js');

module.exports = function (user) {
  app.on('started', function(){
     let Role = app.models.Role;
     let RoleMapping = app.models.RoleMapping;
  }); 
}

related link: Loopback: How to add afterRemote of a model to another model

Upvotes: 1

Related Questions