如何在续集中将三个表连接到一个表的 ID



我正在使用nodejs,express和sequelize构建一个应用程序。在一个API中,我想从4个不同的表中获得一个pid作为输入的数据。我在试着联想。我遵循MVC流程。How to table 1

/* jshint indent: 2 */
// const machine_data = require("./machine_data");
module.exports = function(sequelize, DataTypes) {
return sequelize.define('patient_data', {
sl_no: {
type: DataTypes.INTEGER(11),
autoIncrement: true,
allowNull: false,
primaryKey: true,

},
patient_name: {
type: DataTypes.STRING(35),
allowNull: false
},
p_id: {
type: DataTypes.STRING(100),
allowNull: false,




},

{
associate:function(modals){
patient_data.hasMany(modals.master_session,{ foreignKey: 'p_id' });
patient_data.hasMany(modals.graph_data,{ foreignKey: 'pid' });
patient_data.hasMany(modals.vital_data,{ foreignKey: 'master_id' })
},
},

{
sequelize,
tableName: 'patient_data'
});
};
Table 2
module.exports = function(sequelize, DataTypes) {
return sequelize.define('master_session', {
master_id: {
type: DataTypes.INTEGER(11),
autoIncrement: true,
allowNull: false,
primaryKey: true,


},
session_name: {
type: DataTypes.STRING(35),
allowNull: true
},
{
associate:function(modals){
master_session.belongsTo(modals.patient_data,{ foreignKey: 'p_id' });

},
},

{
sequelize,
tableName: 'master_session'
});
};
table 3
module.exports = function(sequelize, DataTypes) {
return sequelize.define('graph_data', {
sl_no: {
type: DataTypes.INTEGER(11),
autoIncrement: true,
allowNull: false,
primaryKey: true,
foreignKey:true,
refereces:{
model:'patient_data',
key:'p_name'
}



},
document: {
type: DataTypes.STRING(2000),
allowNull: true
},
pid: {
type: DataTypes.STRING(200),
allowNull: true
},
session: {
type: DataTypes.STRING(200),
allowNull: true
},

},
{
associate:function(modals){
graph_data.hasMany(modals.patient_data,{ foreignKey: 'pid' });

},
},

{
sequelize,
tableName: 'graph_data'
});
};

,表4的结构与T3相同。在使用关联之前,我使用代码中的引用来设置外键并在phpmyadmin中手动连接。现在我不知道该怎么做。我想从表1传递p_id在我的请求。主体并从其他表中获取数据。欢迎任何意见。问候。

在您想要获取数据的文件中,导入PatientModel和其他文件。你可以这样做:

patientModel.findAll({
include: [
{
model: masterSessionModel,
attributes: // attributes from master_session
},
{
model: graphDataModel,
attributes: // attributes from graphData
},
// other associated models
]
}).then(myData => { // do something with it })

抽出时间在这里的续集文档中阅读更多内容https://sequelize.org/master/manual/assocs.html#eager-loading-example👈

最新更新