我对 Sequelize 模型有问题。我无法在分离的文件中创建双向关联。所以我有这个简单的代码:
//file one..
module.exports = function (sequelize, DataTypes) {
//models
const Author = sequelize.import(__dirname + '/Author');
const Image = sequelize.define('Image', {
id: {
type: DataTypes.BIGINT,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
author_id: {
type: DataTypes.INTEGER,
required:true,
references:{
model:Author,
key:'id'
},
},
}, {
tableName: 'image',
});
//associations
Image.belongsTo(Author);
return Image;
};
//file two...
module.exports = function init(sequelize, DataTypes) {
//models
const Image = sequelize.import(__dirname + '/Image');
// fields
const Author = sequelize.define('Author', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
username: {
type: DataTypes.STRING(30),
allowNull: false,
unique: true,
}
},
{
tableName: 'author',
});
Author.hasMany(Image);
return Author;
};
这是行不通的。我得到了最大的堆栈调用。我什至不能导入这两个模型中的任何一个。如果我从两个文件之一中删除关联,它就像一个魅力。但我真的需要这种双向关联。
提前致谢...
最佳答案
关联可以这样写:
Aurthor.associate=(models)=>
{
Author.hasMany(Image);
}
还可以运行以下命令来创建默认配置文件。
node_modules/.bin/sequelize init
这将生成一些文件夹 config/config.js、seeders、models/index.js、migrations。
关于node.js - 将分离文件中的关联序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58907052/