【问题标题】:Error: Sequelize Assosication called with something that's not a subclass of Sequelize.Model错误:使用不是 Sequelize.Model 子类的东西调用 Sequelize Assosication
【发布时间】:2020-10-22 11:22:47
【问题描述】:

大家好,当我在我的模型中添加 Sequelize 的关联时,我遇到了一个错误“Error: Text.belongsTo called with something that's not a subclass of Sequelize.Model”,它调用了一个错误我所说的不是Sequelize Model。

这是我的模型的代码,我尝试在 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;

./Text.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;

【问题讨论】:

    标签: node.js postgresql sequelize.js


    【解决方案1】:

    尝试在您的模型文件夹中创建一个 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 模型中

    【讨论】:

      猜你喜欢
      • 2018-04-20
      • 2019-05-21
      • 2020-09-26
      • 1970-01-01
      • 2022-01-04
      • 2020-09-21
      • 1970-01-01
      • 2020-12-20
      • 1970-01-01
      相关资源
      最近更新 更多