译者:飞龙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 。容许重命名关联访问器。 |