Problem with bookshelfjs, error in the return of data from relationships

2

I am interested in applying node with bookshelfjs (ORM), with the bookshelfjs-eloquent plugin and I have a problem when it comes to taking the data of the relations an FK, since all the relations functions return me the length is 0 , having data in their respective tables .

Any ideas on how to get model data through relationships?

I've also tried it from the old way :

Role.fetch({withRelated: ['users']})
   .then(function(role) {
        console.log(role);
  });

The structure of the database: The configuration file of bookshelfjs:

const knex = require('knex')(require('./knexfile').development);
const Bookshelf = require('bookshelf')(knex);
Bookshelf.plugin(require('bookshelf-eloquent'));
Bookshelf.plugin('registry');
Bookshelf.plugin('visibility');
export default Bookshelf;

Models:

user.ts

import Bookshelf from './../config/bookshelf';
import Role from './role';

export default class User extends Bookshelf.Model<any> {
  get tableName() { return 'users'; }
  get hasTimestamps() { return true; }
  get idAttribute() { return 'id'; }
 role = function() {
    return this.belongsTo(Role, 'name');
 }
}

roles.ts

import Bookshelf from './../config/bookshelf';
import User from './user';

export default class Role extends Bookshelf.Model<any> {
 get tableName() { return 'roles'; }
 get hasTimestamps() { return false; }
 get idAttribute() { return 'name'; }

 users = function() {
    return this.hasMany(User, 'id');    
 }
}

index.ts

import Role from './models/role';
import User from './models/user';

(async function(){
 const role = await Role.offset(1).first();
 console.log(role.users());
})();

Result

constructor {
   model: [Function: User],
   length: 0,
   models: [],
   _byId: {},
   eloquent:
    { fetchOptions: {},
      queryBuilderTasksAsync: [],
      withCountColumnsAsync: [],
      withCountColumns: [],
      relationColumns: [],
      withs: {},
      knex:
       { [Function: knex]
         Promise: [Object],
         queryBuilder: [Function: queryBuilder],
         raw: [Function: raw],
         batchInsert: [Function: batchInsert],
         transaction: [Function: transaction],
         initialize: [Function: initialize],
         destroy: [Function: destroy],
         domain: null,
         _events: {},
         _eventsCount: 0,
         _maxListeners: undefined,
         setMaxListeners: [Function: setMaxListeners],
         getMaxListeners: [Function: getMaxListeners],
         emit: [Function: emit],
         addListener: [Function: addListener],
         on: [Function: addListener],
         prependListener: [Function: prependListener],
         once: [Function: once],
         prependOnceListener: [Function: prependOnceListener],
         removeListener: [Function: removeListener],
         removeAllListeners: [Function: removeAllListeners],
         listeners: [Function: listeners],
         listenerCount: [Function: listenerCount],
         eventNames: [Function: eventNames],
         with: [Function],
         select: [Function],
         as: [Function],
         columns: [Function],
         column: [Function],
         from: [Function],
         fromJS: [Function],
         into: [Function],
         withSchema: [Function],
         table: [Function],
         distinct: [Function],
         join: [Function],
         joinRaw: [Function],
         innerJoin: [Function],
         leftJoin: [Function],
         leftOuterJoin: [Function],
         rightJoin: [Function],
         rightOuterJoin: [Function],
         outerJoin: [Function],
         fullOuterJoin: [Function],
         crossJoin: [Function],
         where: [Function],
         andWhere: [Function],
         orWhere: [Function],
         whereNot: [Function],
         orWhereNot: [Function],
         whereRaw: [Function],
         whereWrapped: [Function],
         havingWrapped: [Function],
         orWhereRaw: [Function],
         whereExists: [Function],
         orWhereExists: [Function],
         whereNotExists: [Function],
         orWhereNotExists: [Function],
         whereIn: [Function],
         orWhereIn: [Function],
         whereNotIn: [Function],
         orWhereNotIn: [Function],
         whereNull: [Function],
         orWhereNull: [Function],
         whereNotNull: [Function],
         orWhereNotNull: [Function],
         whereBetween: [Function],
         whereNotBetween: [Function],
         andWhereBetween: [Function],
         andWhereNotBetween: [Function],
         orWhereBetween: [Function],
         orWhereNotBetween: [Function],
         groupBy: [Function],
         groupByRaw: [Function],
         orderBy: [Function],
         orderByRaw: [Function],
         union: [Function],
         unionAll: [Function],
         having: [Function],
         havingRaw: [Function],
         orHaving: [Function],
         orHavingRaw: [Function],
         offset: [Function],
         limit: [Function],
         count: [Function],
         countDistinct: [Function],
         min: [Function],
         max: [Function],
         sum: [Function],
         sumDistinct: [Function],
         avg: [Function],
         avgDistinct: [Function],
         increment: [Function],
         decrement: [Function],
         first: [Function],
         debug: [Function],
         pluck: [Function],
         clearSelect: [Function],
         clearWhere: [Function],
         insert: [Function],
         update: [Function],
         returning: [Function],
         del: [Function],
         delete: [Function],
         truncate: [Function],
         transacting: [Function],
         connection: [Function],
         client: [Object] },
      bookshelf:
       { VERSION: '0.12.1',
         Model: [Object],
         Collection: [Object],
         EventEmitter: [Object],
         usingDomains: false,
         defaultMaxListeners: 10,
         init: [Function],
         listenerCount: [Function],
         NotFoundError: [Function: ErrorCtor],
         EmptyError: [Function: ErrorCtor],
         NoRowsUpdatedError: [Function: ErrorCtor],
         NoRowsDeletedError: [Function: ErrorCtor],
         transaction: [Function: transaction],
         plugin: [Function: plugin],
         knex: [Object],
         registry: {},
         model: [Function],
         collection: [Function],
         resolve: [Function] },
      caseSensitive: false,
      collectionAddMemo: [Function],
      collectionAddMemoCaseSensitive: [Function] },
   relatedData:
    RelationBase {
      targetTableName: 'users',
      targetIdAttribute: 'id',
      type: 'hasMany',
      target: [Function: User],
      foreignKey: 'id',
      foreignKeyTarget: undefined,
      parentId: 'user',
      parentTableName: 'roles',
      parentIdAttribute: 'name',
      parentAttributes: { name: 'user' },
      parentFk: 'user' } }
    
asked by Yasti 10.01.2018 в 19:29
source

1 answer

0

You have a small flaw in the definition of the models it has to be like this:

export default Bookshelf.Model.extend({ /* definición */ });

Then, in the definition of the relationship of a Role it has many Users, the key has to be role (the field of% co_of% what it does of FK) instead of users .

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

Finally, the call to the relationship is possible to do it in 2 ways:

// De esta manera:

const role = await Role.offset(1).first();
console.log('data: ', (await role.users().get()).toJSON());

// O bien de está también:

const roleWithUsers = await Role.with('users').offset(1).first();
console.log('data: ', roleWithUsers.toJSON());
    
answered by 10.01.2018 / 23:00
source