strongloop/loopback-datasource-juggler — pull request #281 by clarkorz (2014-09-03 14:58:36+00:00)
Title: Allows the belongsTo relations in through model to have custom name

This PR allows the belongsTo relations in through model to have custom name.

The key of the PR is determining the `throughRelationName`, which is one of belongsTo relations in through model referencing another model. To make it explicit, it requires the `keyThrough` option (have a default value).

See tests for details.

Examples
==========

### 1.

```js
Physician.hasMany(Patient, {through: Appointment, foreignKey: 'fooId', keyThrough: 'barId'});
Patient.hasMany(Physician, {through: Appointment, foreignKey: 'barId', keyThrough: 'fooId'});
// keyThroughs above will be used to match foreignKeys below
Appointment.belongsTo(Physician, {as: 'foo'}); // foreignKey defaults to 'fooId'
Appointment.belongsTo(Patient, {as: 'bar'}); // foreignKey defaults to 'barId'
```
`keyThrough` defaults to camelize modelTo's name with `Id` postfix, or same as `polymorphic.foreignKey` when `polymorphic.invert = true`. This can match the basic use case of belongsTo. So following code works either.

```js
Physician.hasMany(Patient, {through: Appointment}); // keyThrough defaults to 'patientId'
Patient.hasMany(Physician, {through: Appointment}); // keyThrough defaults to 'physicianId'
// keyThroughs above will be used to match foreignKeys below
Appointment.belongsTo(Physician, {as: 'foo', foreignKey: 'physicianId'});
Appointment.belongsTo(Patient, {as: 'bar', foreignKey: 'patientId'});
```

### 2. Self Through

Twitter like **User-Follow-User**

```js
User.hasMany(User, {as: 'followers', foreignKey: 'followeeId', keyThrough: 'followerId', through: Follow});
User.hasMany(User, {as: 'following', foreignKey: 'followerId', keyThrough: 'followeeId', through: Follow});
Follow.belongsTo(User, {as: 'follower'});
Follow.belongsTo(User, {as: 'followee'});
```

### 3. Polymorphic hasAndBelongsToMany Through
This works already. I only refactor a little.