2016-04-27 25 views
3

你好我是新的Sequelize,我真的失去了如何管理關係。我想設置1:N關係,但是當我看到結果時,我沒有收到關係數據。我現在使用2個表格,medicoshospitals,其中hospitals可以有多個doctors,但doctors只有一個hospital續集:試圖嵌套關聯的錯誤

這是我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" 
      }) 
     } 
     } 
    }); 
     }); 
    }; 

而這一次hospitals之一:models/hospitals.js

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" 
     }) 
    } 
    } 
    }); 
}; 

進出口管理我的模型與此文件models/index.js

'使用嚴格的'

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) 
} 

這個人是我的controller/controllers/personal.js

'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)); 
    }) 

和我的主要index

'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) 

錯誤我越來越:Unhandled rejection Error: hospitals is not associated to doctors!

回答

1

你必須定義在這兩種模式的關係。此外,當您使用belongsTo時,您說醫生屬於醫院,因此外鍵在醫生上定義,此例中的外鍵是醫院的身份。但是,您將醫生ForeignKey設置爲不起作用的醫院的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; 
}; 

UPDATE

您使用加載您的模型文件丟失了很多的是讓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 
} 
+0

仍然無法正常工作。 :(我剛剛更新了我的代碼,這是我得到的錯誤'未處理的拒絕錯誤:醫院沒有與醫生聯繫!' –

+0

查看我的更新回答。 – grimurd

+1

非常感謝,GrimurD先生,你幫了我很多!您的回答是正確的,我只需要添加一些東西'Hospitals.hasMany(醫生,{foreignKey:「idHospital」}) 醫生。belongsTo(醫院,{as:「Hospitals」,foreignKey:「idHospital」})'如果我沒有打擾你,我想如果你加入你的答案,當然,你有獎金。 :) –

0

你試試這個?

Doctors.findAll({ include: Hospitals, }); 

爲了獲取醫學生,以及:

Doctors.findAll({ include: [{ model: Hospitals, include: [Medicos], }], }); 
+0

是的,但我得到這個錯誤未處理拒絕SequelizeDatabaseError:ER_BAD_FIELD_ERROR:未知列「doctors.hospitaleId」在「字段列表」 在Query.formatError –

+0

我想這是因爲你需要定義從關係'醫院'到'醫生'。在續集中,所有的關係都應該被定義爲兩種方式。 – Louy