I ran into a problem and I tried everything including writing with quotes, without quotes and does not work properly . Could someone help me?
var bookshelf = require('../config/bookshelf');
var User= require('./User');
var Frame = require('./Frame');
var Project = bookshelf.Model.extend({
tableName: 'project',
hasTimestamps: true,
user:function() {
return this.belongsToMany(User);
},
frame: function () {
return this.hasMany(Frame);
}
});
module.exports = {
Project: Project
};
... I run into the following error:
Possibly unhandled Error: The model User could not be resolved from the registry plugin.
If I change it back to the actual class...
, user: function(){
return this.belongsToMany(User);
}
... I get the following error instead:
Unhandled rejection Error: A valid target model must be defined for the project belongsToMany relation
You got that error because the User Model is not yet registered in the registery !
So, you can register each model in your app by name and use those names instead of constructors. Look at this wiki how to do that.
Or, instead, disable the registry plugin and require the related models inside the relations methods, like below:
var bookshelf = require('../config/bookshelf')
module.exports = bookshelf.Model.extend({
tableName: 'project',
hasTimestamps: true,
user:function() {
return this.belongsToMany(require('./User'));
},
frame: function () {
return this.hasMany(require('./Frame'));
}
})
Hope it helps
The registry plugin expects either model objects or strings with the name you registered the model:
// User.js
var bookshelf = require('../config/bookshelf');
var User = bookshelf.Model.extend({
tableName : 'users',
hasTimestamps : true
// rest of model ...
});
module.exports = bookshelf.model('User', User);
// Project.js
var bookshelf = require('../config/bookshelf');
var Project = bookshelf.Model.extend({
tableName : 'projects',
hasTimestamps : true,
user : function() {
return this.belongsToMany('User'); // <--- here
},
// rest of model ...
});
module.exports = bookshelf.model('Project', Project);
Notice that there are no requires for User in the Project file.
What I imagine could be happening is that you require('./Users') in the Project
file and require('./Projects') in the User file, son when Project is being _parsed_
by Javascript it hasn't yet parsed the User so it doesn't know what it is yet.
Resolve this by using strings instead of the Model objects and stop the cyclic requires (which is exactly what the registry plugins works for).
Closing this due to lack of activity. If you have anything more to add we can reopen it.
Nice bro. Thank you. It's works!
Most helpful comment
You got that error because the
UserModel is not yet registered in the registery !So, you can register each model in your app by name and use those names instead of constructors. Look at this wiki how to do that.
Or, instead, disable the registry plugin and require the related models inside the relations methods, like below:
Hope it helps