# hasMany(多對多關系)
> 譯者:[飛龍](https://github.com/wizardforcel)
> 來源:[hasMany](https://github.com/dresende/node-orm2/wiki/hasMany)
## hasMany
是多對多的關系(包括連接表)。
例如:`Patient.hasMany('doctors', Doctor, { why: String }, { reverse: 'patients', key: true })`。
病人可以擁有許多不同的醫生。每個醫生可以擁有許多不同的病人。
當你調用`Patient.sync()`時,會創建一個連接表`patient_doctors`。
| 列名稱 | 類型 |
| --- | --- |
| patient_id | Integer |
| doctor_id | Integer |
| why | varchar(255) |
下列函數是可用的:
```
// 獲取所有關聯醫生的列表
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 {
// ...
}
});
// 以及其他
```
要把醫生關聯到病人:
```
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"}`到連接表中。
## API
```
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`。允許重命名關聯訪問器。 |