譯者:飛龍node
來源:hasManygit
是多對多的關係(包括鏈接表)。github
例如:Patient.hasMany('doctors', Doctor, { why: String }, { reverse: 'patients', key: true })
。app
病人能夠擁有許多不一樣的醫生。每一個醫生能夠擁有許多不一樣的病人。函數
當你調用Patient.sync()
時,會建立一個鏈接表patient_doctors
。code
列名稱 | 類型 |
---|---|
patient_id | Integer |
doctor_id | Integer |
why | varchar(255) |
下列函數是可用的:orm
// 獲取全部關聯醫生的列表 patient.getDoctors(function(err, doctors) { // ... }); // 向鏈接表中增長記錄 patient.addDoctors([phil, bob], function(err) { // ... }); // 移除鏈接表中的現有記錄,並增長新的 patient.setDoctors([phil, nephewOfBob], function(err) { // ... }); // 檢查是否某個病人關聯了指定的醫生 patient.hasDoctors([bob], function(err, patientHasBobAsADoctor) { // because that is a totally legit and descriptive variable name if (patientHasBobAsADoctor) { // ... } else { // ... } }); // 從鏈接表中移除指定記錄 patient.removeDoctors([bob], function(err) { // ... }); // 而且全部醫生都有本身的方法來獲取病人 bob.getPatients(function(err, patients) { if (patients.indexOf(you) !== -1) { // woot! } else { // ... } }); // 以及其餘
要把醫生關聯到病人:ip
patient.addDoctor(surgeon, {why: 'remove appendix'}, function(err) { // ... }); // or... surgeon.addPatient(patient, {why: 'remove appendix'}, function(err) { // ... });
這樣會添加{patient_id: 4, doctor_id: 6, why: "remove appendix"}
到鏈接表中。rem
Model.hasMany( name, // String. 關聯名稱 otherModel, // Model. 要關聯的模型 extraProps, // Object. 在鏈接表上出現的額外屬性 opts // Object. 關聯的選項 );
選項名稱 | 類型 | 描述 |
---|---|---|
autoFetch | Boolean | 默認爲false 。若是爲true ,關聯將會自動被獲取。 |
autoFetchLimit | Number | 默認爲1 。自動獲取的深度。 |
key | Boolean | 默認爲false (因爲歷史緣由)。若是爲true ,表中外鍵的列會造成一個組合鍵。 |
mergeTable | String | 鏈接表的自定義名稱 |
mergeId | String | 表明當前模型那一列的自定義名稱 |
mergeAssocId | String | 表明另外一個模型那一列的自定義名稱 |
reverse | String | 默認爲false 。若是爲true ,關聯能夠經過另外一個模型使用指定方法獲取到。 |
getAccessor | String | 默認爲'get' + Name 。容許重命名關聯訪問器。 |
setAccessor | String | 默認爲'set' + Name 。容許重命名關聯訪問器。 |
hasAccessor | String | 默認爲'has' + Name 。容許重命名關聯訪問器。 |
delAccessor | String | 默認爲'del' + Name 。容許重命名關聯訪問器。 |
addAccessor | String | 默認爲'add' + Name 。容許重命名關聯訪問器。 |