书架关联错误

Bookshelf Association Error

我正在尝试创建关联并使用这些关联来创建查询,但我一直收到此错误:

Stack Trace

这是包含我的模型和查询的文件。 (test.js)

import knex from 'knex';
import {
    client,
    host,
    user,
    password,
    database,
    charset
} from './environment/dev';
import bookshelf from 'bookshelf';

const Knex = knex({
    client: client,
    connection: {
        host: host,
        user: user,
        password: password,
        database: database,
        charset: charset
    }
});
const Bookshelf = bookshelf(Knex);
Bookshelf.plugin('registry');

const AccessGroup = Bookshelf.Model.extend({
    tableName: 'AccessGroup',
    idAttribute: 'idAccessGroup',
    users: () => {
        return this.hasMany('User');
    }
});

const User = Bookshelf.Model.extend({
    tableName: 'User',
    idAttribute: 'idUser',
    accessGroup: () => {
        return this.belongsTo('AccessGroup', 'idAccessGroup');
    }
});

const checkUserExist = (userName) => {
    // return new User({
    //     userName
    // }).fetch({withRelated:['accessGroup']});
    return User.forge({userName}).fetch({withRelated: ['accessGroup']});
    // return User.fetchAll({withRelated: ['accessGroup']});
    // return new User({userName}).accessGroup();
}

export { checkUserExist };

基本上我在使用这些关联时遇到了问题。我能够 运行 对我的模型进行基本查询,并从我的数据库中接收准确的数据。我的所有 idAttributes 以及 table 名称都是正确的。我在网上广泛查看,但找不到任何有用的东西。

当我执行基本查询时,

new User({
    userName: 'admin8791'
}).fetch().then(d => {
    console.log(d);
});

结果表明没有关系。

ModelBase {
  attributes:
   { userName: 'admin8791',
     idUser: 8791,
     firstName: 'Jerrell',
     lastName: 'Jones',
     idAccessGroup: 1 },
  _previousAttributes:
   { userName: 'admin8791',
     idUser: 8791,
     firstName: 'Jerrell',
     lastName: 'Jones',
     idAccessGroup: 1 },
  changed: {},
  relations: {},
  cid: 'c1',
  _knex: null }

您必须预先加载关联:

new User({
  userName: 'admin8791'
}).fetch({withRelated: 'accessGroup'}).then(d => {
  console.log(d);
});