gpt4 book ai didi

node.js - 在 Sequelize 中创建多对多关联的问题。 (属于多)

转载 作者:行者123 更新时间:2023-12-03 22:19:33 24 4
gpt4 key购买 nike

当我在两个表之间定义多对多关联时,出现以下错误:

Error: Teacher.belongsToMany called with something that's not a subclass of Sequelize.Model

我将解释我的场景。

我有老师和类(class)表,为了创建关联,我创建了一个名为 course_teachers 的数据透视表。

course_teachers 的迁移代码:
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('courses_teachers', {
id: {
type: Sequelize.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true,
},
course_id: {
type: Sequelize.INTEGER,
allowNull: false,
references: { model: 'courses', key: 'id' },
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
},
teacher_id: {
type: Sequelize.INTEGER,
allowNull: false,
references: { model: 'teachers', key: 'id' },
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
},
created_at: {
type: Sequelize.DATE,
allowNull: false,
},
updated_at: {
type: Sequelize.DATE,
allowNull: false,
},
});
},

down: (queryInterface) => {
return queryInterface.dropTable('courses_teachers');
},
};

楷模:

老师:
import Sequelize, { Model } from 'sequelize';

class Teacher extends Model {
static init(sequelize) {
super.init(
{
name: Sequelize.STRING,
},
{
sequelize,
}
);

return this;
}

static associate(models) {
this.belongsToMany(models.Course, {
foreignKey: 'teacher_id',
through: 'courses_teachers',
as: 'courses',
});
}
}

export default Teacher;

类(class):
import Sequelize, { Model } from 'sequelize';

class Courses extends Model {
static init(sequelize) {
super.init(
{
name: Sequelize.STRING,
},
{
sequelize,
}
);
return this;
}

static associate(models) {
this.belongsToMany(models.Teacher, {
foreignKey: 'course_id',
through: 'courses_teachers',
as: 'teachers',
});
}
}

export default Courses;

错误:
C:\eadfabet\node_modules\sequelize\lib\associations\mixin.js:49 throw new Error(`${this.name}.belongsToMany called with something that's not a subclass of Sequelize.Model`);
^

Error: Teacher.belongsToMany called with something that's not a subclass of Sequelize.Model
at Function.belongsToMany (C:\eadfabet\node_modules\sequelize\lib\associations\mixin.js:49:13)
at Function.associate (C:\eadfabet\src\app\models\Teacher.js:33:10)
at C:\eadfabet\src\database\index.js:26:45
at Array.map (<anonymous>)
at Database.init (C:\eadfabet\src\database\index.js:25:8)
at new Database (C:\eadfabet\src\database\index.js:17:10)
at Object.<anonymous> (C:\eadfabet\src\database\index.js:31:20) ...

[nodemon] app crashed - waiting for file changes before starting...

错误只发生在示范教师身上,在示范类(class)中不会发生。

最佳答案

我错误地指的是示范类(class)。

谢谢@William Prigol Lopes!

关于node.js - 在 Sequelize 中创建多对多关联的问题。 (属于多),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61490149/

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