gpt4 book ai didi

node.js - Sequelize 关联

转载 作者:行者123 更新时间:2023-12-03 22:41:37 26 4
gpt4 key购买 nike

我正在开发一个 Typescript Sequelize 项目,其中我的 /models/index.ts 文件具有以下“导入此目录中的所有模型”功能:

var basename = path.basename(module.filename);
fs
.readdirSync(__dirname)
.filter(function (file) {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(function (file) {
console.log(file);
var model = sequelize['import'](path.join(__dirname, file));
console.log('here');
// NOTE: you have to change from the original property notation to
// index notation or tsc will complain about undefined property.
db[model['name']] = model;
});

然后我的模型结构如下 /models/user.ts :
export default function defineUser(sequelize: Sequelize.Sequelize, DataTypes) {
var User = sequelize.define<UserInstance, UserAttributes>('User', {
email: {
type: Sequelize.STRING,
unique: true,
validate: { isEmail: true }
},
password: Sequelize.STRING
});
return User;
};

但是,我无法将模型从一个文件导入另一个文件,无法执行以下操作:
import * as User from './user'
// ...
// definition of job model
// ...
Job.hasOne(User);

当我得到 Argument of type 'typeof "~/models/job-response"' is not assignable to parameter of type 'Model<any, any>'. 然后:

~/node_modules\sequelize\lib\associations\mixin.js:95 [1] throw new Error(this.name + '.' + Utils.lowercaseFirst(Type.toString()) + ' called with something that\'s not an instance of Sequelize.Model'); [1] ^ [1] [1] Error: Job.function (srcModel, targetModel, options) { [1] Association.call(this); [1] [1] } called with something that's not an instance of Sequelize.Model [1] at Model.hasOne (~\node_modules\sequelize\lib\associations\mixin.js:95:13)



我应该如何访问模型实例,以便将其传递给 hasMany()hasOne() 函数。

最佳答案

在您的模型注册循环运行后,您的所有模型都将在 db.models 上可用,按名称键入。因此,您可以在同一文件或单独的文件中执行以下操作:

db.models.Job.hasOne(db.models.User)

我发现在单独的文件中定义关系很方便,因为如果你想定义关系的双方(即belongsTo/hasMany),那么无论如何你都必须这样做(以避免循环依赖)

关于node.js - Sequelize 关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41662765/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com