gpt4 book ai didi

javascript - bookshelf.js 关系有很多错误

转载 作者:数据小太阳 更新时间:2023-10-29 05:54:47 27 4
gpt4 key购买 nike

我在使用 Bookshelf 调用 hasMany 时遇到以下错误:

 A valid target model must be defined for the roles hasMany relation

Angular 色.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;

用户.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;

用法:

new Role({ id: req.params.id })
.fetch({ require: true, withRelated:['users'] })
.then(function (role) {
role.users().fetch().then(function(users) {
console.log('users: ' + users);
});
})

最佳答案

我将我的模型引用为字符串,并使用 Bookshelf 的 registry plugin .

var bookshelf = new Bookshelf( knex );
bookshelf.plugin( 'registry' );

然后我定义并创建一个模型:

var userModel = /*do bookshelf things*/;
bookshelf.model( 'User', userModel );

然后当我创建一个.hasMany时,我使用一个字符串来引用。

users: function() {
return this.hasMany( 'User', 'roleId' );
},

关于javascript - bookshelf.js 关系有很多错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26998033/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com