mysql - 书架关联错误
问题描述
我正在尝试创建关联并使用这些关联来创建查询,但我一直收到此错误:
这是包含我的模型和查询的文件。(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 以及表名都是正确的。我在网上查了很多资料,但找不到任何有用的东西。
当我执行基本查询时,
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);
});
推荐阅读
- php - Symfony 3.4 扩展在迁移后不工作
- loops - for循环中的索引超出范围(重复)
- javascript - 使用 Java 脚本在表格中选择复选框
- google-cloud-dataflow - 如何为在 Direct Runner 上运行的 apache 光束管道设置日志级别
- sql - SQL Server 通过避免“Case 表达式只能嵌套到级别 10”来使用 IIF 计算列
- c++ - 新旧位置之间的速度
- performance - 如何设计 Bigtable Key
- ios - 启动时不显示 API 结果
- scip - 什么是 SCIP 安装过程中发生的“libzimpl-NOTFOUND”错误
- python - 使用 docker-compose 在 Django 中不存在