我的 Node JS 应用程序中有两个模型,用户和公司。当我在获取公司时尝试使用 include 函数时,出现错误:
message: "users is not associated to companies!"
这是用户模型
import { Sequelize, DataTypes } from 'sequelize';
import { Application } from '../declarations';
export default function (app: Application) {
const sequelizeClient: Sequelize = app.get('sequelizeClient');
const users = sequelizeClient.define('users', {
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true
},
password: {
type: DataTypes.STRING,
allowNull: true
},
role: {
type: DataTypes.STRING,
allowNull: true,
},
language: {
type: DataTypes.STRING,
allowNull: false,
defaultValue: 'en',
},
firstName: {
type: DataTypes.STRING,
allowNull: false
},
lastName: {
type: DataTypes.STRING,
allowNull: false,
},
}, {
underscored: true,
hooks: {
beforeCount(options: any) {
options.raw = true;
}
}
});
// eslint-disable-next-line no-unused-vars
(users as any).associate = function (models: any) {
(users as any).belongsTo(models.companies, {
foreignKey: 'companyId',
allowNull: true,
onDelete: "CASCADE",
});
};
return users;
}
和公司模型:
import { Sequelize, DataTypes, Model } from 'sequelize';
import { Application } from '../declarations';
export default function (app: Application) {
const sequelizeClient: Sequelize = app.get('sequelizeClient');
const companies = sequelizeClient.define('companies', {
name: {
type: DataTypes.STRING,
allowNull: false
},
phone: {
type: DataTypes.STRING,
allowNull: false,
defaultValue: '',
},
email: {
type: DataTypes.STRING,
allowNull: false,
defaultValue: '',
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: true,
},
}, {
underscored: true,
hooks: {
beforeCount(options: any) {
options.raw = true;
}
}
});
// eslint-disable-next-line no-unused-vars
(companies as any).associate = function (models: any) {
(companies as any).hasMany(models.users);
(companies as any).hasMany(models.patients);
};
return companies;
}
和包含功能
function getSuperAdmin() {
return (context: HookContext) => {
const sequelizeClient = context.app.get("sequelizeClient");
context.params.sequelize = {
include: [
{
model: sequelizeClient.models.users,
as: 'users',
required: false,
where: {
'$users.role$': 'super_admin'
}
}
],
};
return context;
}
}
当我在用户查询中包含公司模型时,它可以正常工作。但不是反过来。有任何想法吗?
谢谢