错误:使用不是 Sequelize.Model 子类的东西调用 Sequelize Assosication



大家好,我有个错误">错误:用不是Sequelize.Model子类的东西调用Text.belongsTo;当我在我的模型中添加Sequelize的关联时,它调用了一个错误,我称之为"不是Sequelize模型"。

这是我的模型的代码,我试图在Post模型和Text模型之间创建一个关联。

/Post.js

const { DataTypes } = require('sequelize');
const sequelize = require('../../db/sequelize.setup');
const Text = require('./Text');
const Post = sequelize.define(
'Post',
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
allowNull: false,
},
title: {
type: DataTypes.STRING(),
allowNull: false,
},
tags: {
type: DataTypes.ARRAY(DataTypes.INTEGER),
allowNull: true,
},
items: {
type: DataTypes.ARRAY(DataTypes.INTEGER),
allowNull: false,
},
author: {
type: DataTypes.INTEGER,
},
},
{
modelName: 'Post',
timestamps: true,
}
);
Post.hasMany(Text, {
as: 'Text',
foreignKey: 'post_id',
sourceKey: 'id',
});
module.exports = Post;

/文本.js

const { DataTypes } = require('sequelize');
const sequelize = require('../../db/sequelize.setup');

const Post = require('./Post');

const Text = sequelize.define(
'Text',
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
allowNull: false,
},
text: {
type: DataTypes.STRING(),
allowNull: false,
},
},
{
modelName: 'Text',
timestamps: true,
}
);

Text.belongsTo(Post, { as: 'Post', foreignKey: 'post_id', targetKey: 'id' });

module.exports = Text;

尝试在models文件夹中创建一个index.js文件,并在其中创建类似的关联

const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
db.posts=require("./post.js")(sequlize,sequlize);
db.texts=require....
db.posts.hasMany(db.texts, { foreignKey: 'postId' });
db.texts.belongsTo(db.posts, { foreignKey: 'postId' });

并将postId放入text.js模型中

最新更新