Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bookshelf.js relationship hasMany error

I'm getting the following error on a hasMany call using Bookshelf:

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

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

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);
  });
})
like image 594
SirJay Avatar asked Nov 18 '14 15:11

SirJay


2 Answers

I reference my models as strings, and use Bookshelf's registry plugin.

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.

users: function() {
  return this.hasMany( 'User', 'roleId' );
},
like image 64
clay Avatar answered Nov 17 '22 18:11

clay


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

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);
like image 2
Oscar Oceguera Avatar answered Nov 17 '22 17:11

Oscar Oceguera