书架关联错误

dzhpxtsq  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(344)

我正在尝试创建关联并使用这些关联创建查询,但一直收到以下错误:
堆栈跟踪
这是我的模型和查询文件(测试.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 };

基本上我对使用这些关联有问题。我能够在我的模型上运行基本查询,并从数据库中接收准确的数据。我所有的id属性和表名都是正确的。我在网上查了很多,但找不到任何有用的东西。
当我执行基本查询时,

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 }
dwthyt8l

dwthyt8l1#

必须立即加载关联:

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

相关问题