[英]bookshelf.js relationship hasMany error
I'm getting the following error on a hasMany
call using Bookshelf: 我在使用Bookshelf的
hasMany
调用时收到以下错误:
A valid target model must be defined for the roles hasMany relation
Role.js Role.js
var Data = require('../server-includes/Data'),
User = require('./User');
var Role = Data.bookshelf.Model.extend({
tableName: 'roles',
users: function() {
return this.hasMany(User, 'role_id');
}
});
module.exports = Role;
User.js user.js的
var Data = require('../server-includes/Data'),
Role = require('./Role');
var User = Data.bookshelf.Model.extend({
tableName: 'users',
role: function() {
return this.belongsTo(Role, 'id');
},
};
module.exports = User;
Usage: 用法:
new Role({ id: req.params.id })
.fetch({ require: true, withRelated:['users'] })
.then(function (role) {
role.users().fetch().then(function(users) {
console.log('users: ' + users);
});
})
I reference my models as strings, and use Bookshelf's registry plugin . 我将我的模型作为字符串引用,并使用Bookshelf的注册表插件 。
var bookshelf = new Bookshelf( knex );
bookshelf.plugin( 'registry' );
Then I define and create a model: 然后我定义并创建一个模型:
var userModel = /*do bookshelf things*/;
bookshelf.model( 'User', userModel );
Then when I create a .hasMany
, I use a string to reference. 然后当我创建一个
.hasMany
,我使用一个字符串来引用。
users: function() {
return this.hasMany( 'User', 'roleId' );
},
post.js post.js
Bookshelf.plugin('registry')
var Category = require('./category')
var Post = Bookshelf.Model.extend({
tableName: 'posts',
hasTimestamps: true,
categories: function () {
return this.belongsTo('Category', 'category_id');
},
});
module.exports = Bookshelf.model('Post',Post);
category.js category.js
Bookshelf.plugin('registry');
var Post = require('./post');
var Category = Bookshelf.Model.extend({
tableName: 'categories',
hasTimestamps: true,
posts : function () {
return this.hasMany('Post');
}
});
module.exports = Bookshelf.model('Category', Category);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.