Javascript Sequelize:尝试创建嵌套关联时出错
你好,我是Sequelize的新手,我真的不知道如何管理关系。我想设置1:N关系,但当我看到结果时,我没有收到关系数据。目前我正在使用两个表,Javascript Sequelize:尝试创建嵌套关联时出错,javascript,node.js,sequelize.js,Javascript,Node.js,Sequelize.js,你好,我是Sequelize的新手,我真的不知道如何管理关系。我想设置1:N关系,但当我看到结果时,我没有收到关系数据。目前我正在使用两个表,medicos和hospitals,其中医院可以有许多医生,但医生只有一家医院 这是我的doctors表格:models/doctors.js module.exports = function(sequelize, DataTypes) { return sequelize.define('doctors', { id
medicos
和hospitals
,其中医院可以有许多医生
,但医生
只有一家医院
这是我的doctors
表格:models/doctors.js
module.exports = function(sequelize, DataTypes) {
return sequelize.define('doctors', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING,
allowNull: false
},
lastName: {
type: DataTypes.STRING,
allowNull: false
},
SSN: {
type: DataTypes.STRING,
allowNull: false
},
speciality: {
type: DataTypes.ENUM('Doctor','Geriatrician'),
allowNull: false
},
idHospital: {
type: DataTypes.INTEGER(11),
allowNull: false,
},
}, {
tableName: 'doctors',
freezeTableName: true,
classMethods: {
associate: models => {
models.doctors.belongsTo(models.hospitals, {
foreignKey: "idHospital"
})
}
}
});
});
};
module.exports = function(sequelize, DataTypes) {
return sequelize.define('hospitals', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING,
allowNull: false
},
idData: {
type: DataTypes.INTEGER(11),
allowNull: false,
references: {
model: 'data',
key: 'id'
}
},
}, {
tableName: 'hospitals',
freezeTableName: true,
classMethods: {
associate: models => {
models.hospitals.hasMany(models.doctors, {
foreignKey: "idHospital"
})
}
}
});
};
'use strict'
module.exports = (Doctors) => {
const express = require('express'),
router = express.Router()
router
.get('/', (req, res) => {
Doctors.findAll({ include: [{ model: Hospitals, include: [Doctors], }], }).then((Doctors) => console.log(Doctors));
})
这是医院
one:models/hospitals.js
module.exports = function(sequelize, DataTypes) {
return sequelize.define('doctors', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING,
allowNull: false
},
lastName: {
type: DataTypes.STRING,
allowNull: false
},
SSN: {
type: DataTypes.STRING,
allowNull: false
},
speciality: {
type: DataTypes.ENUM('Doctor','Geriatrician'),
allowNull: false
},
idHospital: {
type: DataTypes.INTEGER(11),
allowNull: false,
},
}, {
tableName: 'doctors',
freezeTableName: true,
classMethods: {
associate: models => {
models.doctors.belongsTo(models.hospitals, {
foreignKey: "idHospital"
})
}
}
});
});
};
module.exports = function(sequelize, DataTypes) {
return sequelize.define('hospitals', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING,
allowNull: false
},
idData: {
type: DataTypes.INTEGER(11),
allowNull: false,
references: {
model: 'data',
key: 'id'
}
},
}, {
tableName: 'hospitals',
freezeTableName: true,
classMethods: {
associate: models => {
models.hospitals.hasMany(models.doctors, {
foreignKey: "idHospital"
})
}
}
});
};
'use strict'
module.exports = (Doctors) => {
const express = require('express'),
router = express.Router()
router
.get('/', (req, res) => {
Doctors.findAll({ include: [{ model: Hospitals, include: [Doctors], }], }).then((Doctors) => console.log(Doctors));
})
我用这个文件管理我的模型models/index.js
module.exports = function(sequelize, DataTypes) {
return sequelize.define('doctors', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING,
allowNull: false
},
lastName: {
type: DataTypes.STRING,
allowNull: false
},
SSN: {
type: DataTypes.STRING,
allowNull: false
},
speciality: {
type: DataTypes.ENUM('Doctor','Geriatrician'),
allowNull: false
},
idHospital: {
type: DataTypes.INTEGER(11),
allowNull: false,
},
}, {
tableName: 'doctors',
freezeTableName: true,
classMethods: {
associate: models => {
models.doctors.belongsTo(models.hospitals, {
foreignKey: "idHospital"
})
}
}
});
});
};
module.exports = function(sequelize, DataTypes) {
return sequelize.define('hospitals', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING,
allowNull: false
},
idData: {
type: DataTypes.INTEGER(11),
allowNull: false,
references: {
model: 'data',
key: 'id'
}
},
}, {
tableName: 'hospitals',
freezeTableName: true,
classMethods: {
associate: models => {
models.hospitals.hasMany(models.doctors, {
foreignKey: "idHospital"
})
}
}
});
};
'use strict'
module.exports = (Doctors) => {
const express = require('express'),
router = express.Router()
router
.get('/', (req, res) => {
Doctors.findAll({ include: [{ model: Hospitals, include: [Doctors], }], }).then((Doctors) => console.log(Doctors));
})
“严格使用”
module.exports = (connection) => {
const Users = connection.import('users'),
States = connection.import('states'),
Cities = connection.import('cities'),
Data = connection.import('data'),
Patient = connection.import('patients'),
Hospitals = connection.import('hospitals'),
Doctors = connection.import('doctors'),
Doctors.belongsTo(Hospitals)
Hospitals.hasMany(Doctors)
require('../controllers/patients')(Users)
require('../controllers/personal')(Doctors, Hospitals)
}
这是我的控制器
/controllers/personal.js
module.exports = function(sequelize, DataTypes) {
return sequelize.define('doctors', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING,
allowNull: false
},
lastName: {
type: DataTypes.STRING,
allowNull: false
},
SSN: {
type: DataTypes.STRING,
allowNull: false
},
speciality: {
type: DataTypes.ENUM('Doctor','Geriatrician'),
allowNull: false
},
idHospital: {
type: DataTypes.INTEGER(11),
allowNull: false,
},
}, {
tableName: 'doctors',
freezeTableName: true,
classMethods: {
associate: models => {
models.doctors.belongsTo(models.hospitals, {
foreignKey: "idHospital"
})
}
}
});
});
};
module.exports = function(sequelize, DataTypes) {
return sequelize.define('hospitals', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING,
allowNull: false
},
idData: {
type: DataTypes.INTEGER(11),
allowNull: false,
references: {
model: 'data',
key: 'id'
}
},
}, {
tableName: 'hospitals',
freezeTableName: true,
classMethods: {
associate: models => {
models.hospitals.hasMany(models.doctors, {
foreignKey: "idHospital"
})
}
}
});
};
'use strict'
module.exports = (Doctors) => {
const express = require('express'),
router = express.Router()
router
.get('/', (req, res) => {
Doctors.findAll({ include: [{ model: Hospitals, include: [Doctors], }], }).then((Doctors) => console.log(Doctors));
})
和我的主索引
'use strict'
const express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
Sequelize = require('sequelize'),
port = process.env.PORT || 3000,
app = express(),
connection = new Sequelize('Matadero', 'root', 'root');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:true}))
app.set('view engine', 'ejs')
app.set('views', path.resolve(__dirname, 'client', 'views'))
app.use(express.static(path.resolve(__dirname, 'client')))
app.get('/', (req, res) => {
res.render('admin/index.ejs')
})
const onListening = () => console.log(`Successful connection at port: ${port}`)
require('./models')(connection)
app.listen(port, onListening)
const patients = require('./controllers/patients'),
personal = require('./controllers/personal')
app.use('/api/patients', patients)
app.use('/api/personal', personal)
我收到的错误:未处理的拒绝错误:医院与医生没有关联代码>您尝试过这个吗
Doctors.findAll({ include: Hospitals, });
要同时获取Medico,请执行以下操作:
Doctors.findAll({ include: [{ model: Hospitals, include: [Medicos], }], });
您必须在两个模型上定义关系。另外,当您使用belongsTo时,您表示医生属于医院,因此外键是在医生上定义的,在本例中外键是医院的id。但是你把医生的外号设置为医院的id,这是行不通的
module.exports = function(sequelize, DataTypes) {
var doctors = sequelize.define('doctors', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING,
allowNull: false
},
lastName: {
type: DataTypes.STRING,
allowNull: false
},
SSN: {
type: DataTypes.STRING,
allowNull: false
},
idData: {
type: DataTypes.INTEGER(11),
allowNull: false,
references: { // I'd recommend using the associate functions instead of creating references on the property, only causes confusion from my experience.
model: 'data',
key: 'id'
}
},
speciality: {
type: DataTypes.ENUM('Doctor','Geriatrician'),
allowNull: false
},
// This is the foreignKey property which is referenced in the associate function on BOTH models.
idHospital: {
type: DataTypes.INTEGER(11),
allowNull: false // Using allowNull makes this relationship required, on your model, a doctor can't exist without a hospital.
},
}, {
tableName: 'doctor',
freezeTableName: true,
classMethods: {
associate: models => {
doctors.belongsTo(models.hospitals, {
foreignKey: "idHospital"
})
}
}
});
return doctors;
};
module.exports = function(sequelize, DataTypes) {
var hospital = sequelize.define('hospitals', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING,
allowNull: false
},
idData: {
type: DataTypes.INTEGER(11),
allowNull: false,
references: {
model: 'data',
key: 'id'
}
},
}, {
tableName: 'hospitals',
freezeTableName: true,
classMethods: {
associate: models => {
hospital.hasMany(models.doctors, {
foreignKey: 'idHospital'
}
}
}
});
return hospital;
};
更新
用于加载模型的文件缺少使sequelize工作所需的大量代码。您需要手动调用每个模型上的关联函数。sequelize提供了一个标准实现,我对其进行了一些修改,以使用您的代码
var fs = require("fs");
var path = require("path");
var Sequelize = require("sequelize");
module.exports = (connection) => {
var models = {};
// Here we read in all the model files in your models folder.
fs
// This assumes this file is in the same folder as all your
// models. Then you can simply do require('./modelfoldername')
// to get all your models.
.readdirSync(__dirname)
// We don't want to read this file if it's in the folder. This
// assumes it's called index.js and removes any files with
// that name from the array.
.filter(function (file) {
return (file.indexOf(".") !== 0) && (file !== "index.js");
})
// Go through each file and import it into sequelize.
.forEach(function (file) {
var model = connection.import(path.join(__dirname, file));
models[model.name] = model;
});
// For each model we run the associate function on it so that sequelize
// knows that they are associated.
Object.keys(models).forEach(function (modelName) {
if ("associate" in models[modelName]) {
models[modelName].associate(models);
}
});
models.connection = connection;
models.Sequelize = Sequelize;
return models
}
是的,但是我得到了这个未处理的拒绝后遗症tabaseError:ER\u BAD\u FIELD\u error:Query.formatError的'FIELD list'中的未知列'doctors.hospitaleId'。我想这是因为你需要定义一个从Hospital
到Doctor
的关系。在sequelize中,应双向定义所有关系。仍不起作用:(我刚刚更新了我的代码。这是我得到的错误未经处理的拒绝错误:医院与医生无关!
非常感谢你,格里默德先生。你帮了我很多忙!你的答案是正确的,我只需添加一些医院。有很多(医生,{foreignKey:{idHospital})医生。以下是(医院,{as:“医院”,foreignKey:“idHospital”})
如果我不打扰你,我希望你能补充你的答案,当然,你得到了赏金。)@CanKerDiAlike很高兴它起作用了。我的代码示例组合本应该起作用的,但我不明白为什么你必须添加这些额外的行。哦,不管怎样,它现在都起作用了:)哦,因为它正在寻找另一个名为HospitalID的id夏令营,我必须通过编写手动设置。是的,我哭了一个星期,因为我不知道怎么做.你救了我的命。