我已经定义了这个模型:
const Sequelize = require('sequelize');
const db = require("../database/db")
var Reparacion = db.sequelize.define('reparaciones', {
id: {
type: Sequelize.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true,
},
descripcion: {
type: Sequelize.STRING(255),
allowNull: true
},
fecha_inicio: {
type: Sequelize.DATEONLY,
allowNull: true
},
fecha_fin: {
type: Sequelize.DATEONLY,
allowNull: true
},
},{});
module.exports=Reparacion在其他模型中,当我在其他模型中定义foreing键时,方法HasMany和belongsTo无法工作,因为我在函数上调用了它们:
const Reparacion = require("./reparacion")
console.log(typeof(Vehiculo))
console.log(typeof(Reparacion))
Vehiculo.hasMany(Reparacion,{foreingKey:"vehiculoId", onDelete: 'cascade', sourceKey:"matricula"})
Reparacion.belongsTo(Vehiculo)两个控制台日志返回:“函数”
为了正确定义关联,我必须改变什么??
编辑
这是"Vehiculo“模式:
const Sequelize = require('sequelize');
const db = require("../database/db")
var Vehiculo = db.sequelize.define('vehiculos', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true,
allowNull: true
},
matricula: {
type: Sequelize.STRING(45),
allowNull: false,
primaryKey: true,
},
marca: {
type: Sequelize.STRING(50),
allowNull: true
},
modelo: {
type: Sequelize.STRING(50),
allowNull: true
},
anio: {
type: Sequelize.INTEGER,
allowNull: true
},
color: {
type: Sequelize.STRING(20),
allowNull: true
},
puertas: {
type: Sequelize.INTEGER,
allowNull: true
},
motor: {
type: Sequelize.STRING(20),
allowNull: true
},
},{});
const Reparacion = require("./reparacion")
Vehiculo.hasMany(Reparacion,{foreingKey:"vehiculoMatricula", onDelete: 'cascade', sourceKey:"matricula"})
Reparacion.belongsTo(Vehiculo)
module.exports=Vehiculo发布于 2021-05-13 12:20:34
那么,预计typeof Vehiculo和typeof Reparacion将返回一个function,因为每个构造函数或类都是JS中的函数,所以当您为实体创建模型时,它返回一个函数/构造函数,该函数/构造函数可以为您创建一个实体的实例。所以这是没有问题的。
实际上,文档显示了类似的代码https://sequelize.org/master/manual/assocs.html。
https://stackoverflow.com/questions/67519060
复制相似问题