gpt4 book ai didi

javascript - sequelize 定义关联时出现错误

转载 作者:行者123 更新时间:2023-12-03 22:32:01 25 4
gpt4 key购买 nike

我试图定义 Sequelize 关联,但在定义 hasMany 关系时出错error throw new Error(${this.name}.hasMany called with something that's not a subclass of Sequelize.Model);它是 account 和 account_type 之间的一对多关系,其中

  • account_type has many account
  • account belongs to account_type

  • 这是我的代码
    模型/account.js

    const Sequelize = require('sequelize');
    const sequelize = require('../../helper/dbConnection');

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

    const account = sequelize.define('account', {
    id: {
    primaryKey: true,
    allowNull: true,
    autoIncrement: true,
    type: Sequelize. INTEGER,
    },
    account: {
    allowNull: false,
    unique: true,
    type: Sequelize.STRING
    },
    nominal: {
    allowNull: false,
    type: Sequelize.DOUBLE,
    },
    description: {
    allowNull: true,
    type: Sequelize.TEXT,
    },
    type_id: {
    allowNull: false,
    type: Sequelize.INTEGER,
    references: {
    model: 'account_type',
    key: 'id'
    },
    onUpdate: 'cascade',
    onDelete: 'cascade'
    },
    is_deleted: {
    allowNull: false,
    default: false,
    type: Sequelize.BOOLEAN,
    },
    created_at: Sequelize.DATE,
    updated_at: Sequelize.DATE,
    });

    account.belongsTo(accountType, { foreignKey: 'type_id' });

    module.exports = account;

    模型/accountType.js

    const Sequelize = require('sequelize');
    const sequelize = require('../../helper/dbConnection');

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

    const accountType = sequelize.define('account_type', {
    id: {
    allowNull: false,
    autoIncrement: true,
    primaryKey: true,
    type: Sequelize.INTEGER
    },
    type: {
    allowNull: false,
    unique: true,
    type: Sequelize.STRING,
    },
    description: {
    allowNull: true,
    type: Sequelize.TEXT
    },
    parent_id: {
    allowNull: true,
    type: Sequelize.INTEGER,
    references: {
    model: 'account_type',
    key: 'id'
    },
    onUpdate: 'cascade',
    onDelete: 'cascade'
    },
    created_at: Sequelize.DATE,
    updated_at: Sequelize.DATE,
    });

    accountType.hasMany(account);

    module.exports = accountType;

    我已经尝试按照文档进行操作,但出现错误,我真的卡住了,请帮助我任何人

    最佳答案

    感谢 ankh 先生,这段代码存在循环依赖问题
    解决方案只是 models/account.jsmodels/accountType.js 中的 1 个文件 中定义关联

    关于javascript - sequelize 定义关联时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66102448/

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