sequelize.js - 续集急切负载问题:子级未与父级关联
问题描述
我有以下包含声明:
context.params.sequelize = {
raw: false,
include: [{
model: organisationUsers,
required: false,
include: [{
required: false,
model: roles,
where: roleId ? { roleId } : undefined,
}],
}],
}
我有以下数据结构:OrganizationUsers:
const organisationUsers = sequelizeClient.define('organisation_users', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
roleId: {
type: DataTypes.INTEGER,
allowNull: true,
},
organisationId: {
type: DataTypes.INTEGER,
allowNull: true,
},
userId: {
type: DataTypes.INTEGER,
allowNull: true,
},
}, {
hooks: {
beforeCount(options) {
options.raw = true;
},
}
});
// eslint-disable-next-line no-unused-vars
organisationUsers.associate = (models) => {
// Define associations here
// See http://docs.sequelizejs.com/en/latest/docs/associations/
organisationUsers.belongsTo(models.organisations, { foreignKey: 'organisationId' });
organisationUsers.belongsTo(models.roles, { foreignKey: 'roleId' });
organisationUsers.belongsTo(models.users, { foreignKey: 'userId' });
};
角色:
const roles = sequelizeClient.define('roles', {
name: {
type: DataTypes.STRING,
allowNull: false
}
}, {
hooks: {
beforeCount(options) {
options.raw = true;
}
},
});
// eslint-disable-next-line no-unused-vars
roles.associate = (models) => {
// Define associations here
// See http://docs.sequelizejs.com/en/latest/docs/associations/
roles.belongsToMany(models.permissions, { through: 'role_permissions' });
roles.hasMany(organisationUsers(app), { foreignKey: 'roleId' });
};
和用户:
const users = sequelizeClient.define('users', {
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true
}
},
password: {
type: DataTypes.STRING,
allowNull: false
},
}, {
hooks: {
beforeCount(options) {
options.raw = true;
}
}
});
// eslint-disable-next-line no-unused-vars
users.associate = (models) => {
// Define associations here
// See http://docs.sequelizejs.com/en/latest/docs/associations/
users.hasMany(organisationUsers(app), { foreignKey: 'userId' });
};
如果 OrganisationUsers 表包含一个 roleId、userId 和 organizationId 一切正常,但如果 OrganisationUsers 表中缺少关联,则会收到以下错误:
SequelizeEagerLoadingError: roles is not associated to organisation_users!
我不知道如何处理这个错误,我已经阅读了包括 required: false 声明,如上你可以看到我已经尝试过。
我不确定问题是否是由于嵌套包含?如果我删除嵌套的包含,使其看起来像这样:
context.params.sequelize = {
raw: false,
include: [{
model: organisationUsers,
}],
}
比一切都好。
如果您有任何想法、建议、建议等...请告诉我。
问候,埃米尔
解决方案
推荐阅读
- .net - Microsoft Dynamics Nav2009 在我尝试运行时立即关闭
- python - 加载 TensorFlow keras 模型 (.h5) 时出错
- php - php - 即使选择器为空也通过
- c++ - SEAL:如何以模系数的形式读取 Relinkkeys 数据?
- markdown - 如何从单个 Markdown 文件创建多个页面?
- git - `git log --all --full-history --find-renames --follow
` 不返回文件创建 - sharepoint - Microsoft graph Api 获取共享点列表项,使用查询 $filter=indexOf 或 $search 未找到项
- reactjs - src\App.js Line 5:3: 'state' is not defined no-undef
- java - 如何使用 TestNG、Java 和 Appium 在多个移动设备上并行运行每个测试?
- nuxt.js - window.removeEventListener 在 Nuxt JS 中不起作用