我是sequelize的新手,我正在尝试创建两个表。用户和项目。我已经为每个表定义了一个模型,称为UserModel和ProjectModel,当我尝试将项目与用户关联时,我得到了这个错误:
使用不是Sequelize子类的内容调用belongsTo。Model
下面是我定义每个模型的文件:
用户.js
module.exports = (sequelize, DataType) => {
const UserModel = sequelize.define("user", {
id: {
type: DataType.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
email: {
type: DataType.STRING,
allowNull: false,
isEmail: {
msg: "The format of the e-mail is not correct"
},
validate: {
notNull: {
msg: "E-mail cannot be empty"
}
}
},
name: {
type: DataType.STRING,
is: /^[a-zA-Z ]+$/i,
allowNull: false,
validate: {
notNull: {
msg: "Name cannot be empty"
}
}
},
surname: {
type: DataType.STRING,
is: /^[a-zA-Z ]+$/i,
allowNull: false,
validate: {
notNull: {
msg: "Surname cannot be empty"
}
}
}
});
UserModel.associate = (models) => {
UserModel.hasMany(models.ProjectModel, {
foreignKey: "userID"
})
}
return UserModel;
};
项目.js
module.exports = (sequelize, DataType) => {
const ProjectModel = sequelize.define("project", {
id: {
type: DataType.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
name: {
type: DataType.STRING,
is: /^[a-zA-Z ]+$/i,
allowNull: false,
validate: {
notNull: {
msg: "Name cannot be empty"
}
}
},
body: {
type: DataType.TEXT,
allowNull: false,
validate: {
notNull: {
msg: "Body cannot be empty"
}
}
},
status: {
type: DataType.ENUM("active", "inactive", "declined", "completed"),
allowNull: false,
validate: {
notNull: {
msg: "Status cannot be empty"
}
}
},
userID: {
type: DataType.INTEGER,
allowNull: false,
validate: {
notNull: {
msg: "userID cannot be empty"
}
},
references: {
model: UserModel,
key: "id"
}
}
});
ProjectModel.associate = (models) => {
ProjectModel.belongsTo(models.UserModel, {
foreignKey: "userID"
});
}
ProjectModel.belongsTo(UserModel, {
foreignKey: "userID"
});
return ProjectModel;
}
我哪里做错了?
2条答案
按热度按时间7uhlpewt1#
最后,我找到了解决问题的方法,例如:
使用变量模型。UserModel我引用了模型返回的变量。而不是这样,你必须写表的名称。所以,在我的例子中,正确的函数是:
wgx48brx2#
不要在另一个模型文件中导入模型。就像如果你写了一个.belongsTo(B)文件,那么不要将A文件导入B文件。