You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Is a many to many relationship (includes join table).
Eg: Patient.hasMany('doctors', Doctor, { why: String }, { reverse: 'patients', key: true }).
Patient can have many different doctors. Each doctor can have many different patients.
This will create a join table patient_doctors when you call Patient.sync():
column name
type
patient_id
Integer
doctor_id
Integer
why
varchar(255)
The following functions will be available:
// Get the list of associated doctorspatient.getDoctors(function(err,doctors){// ...});// Add entries to the join tablepatient.addDoctors([phil,bob],function(err){// ...});// Remove existing entries in join table and add new onespatient.setDoctors([phil,nephewOfBob],function(err){// ...});// Checks if patient is associated to specified doctorspatient.hasDoctors([bob],function(err,patientHasBobAsADoctor){// because that is a totally legit and descriptive variable nameif(patientHasBobAsADoctor){// ...}else{// ...}});// Remove specific entries from the join tablepatient.removeDoctors([bob],function(err){// ...});// And all of the doctor's have their own methods for selecting patients!bob.getPatients(function(err,patients){if(patients.indexOf(you)!==-1){// woot!}else{// ...}});// and so on and so forth
which will add {patient_id: 4, doctor_id: 6, why: "remove appendix"} to the join table.
API
Model.hasMany(name,// String. Association nameotherModel,// Model. The model we're association toextraProps,// Object. Extra properties that will appear on the join tableopts// Object. Options for the association);
opts
option name
type
description
autoFetch
Boolean
Default: false. If true, association will be automatically fetched with parent.
autoFetchLimit
Number
Default: 1. How many levels deep to auto fetch
key
Boolean
Default: false (for historical reasons). If true, foreign key columns in the table will form a composite key.
mergeTable
String
Custom name for the merge table
mergeId
String
Custom name for column referencing this model
mergeAssocId
String
Custom name for column referencing other model
reverse
String
Default: false. If true, association will be accessible from the other model with the specified name.