neumino/thinky — pull request #122 by simonratner (2014-09-15 23:54:03+00:00)
Title: Support merging additional link fields into joined docs

Hacky hack to support storing additional fields in the n-n linking table. Example:
```javascript
var A = thinky.createModel('A', {id: String});
var B = thinky.createModel('B', {id: String});
var A_B = thinky.createModel('A_B', {id: String, extra: String});
A.hasAndBelongsToMany(B, 'bs', 'id', 'id');
B.hasAndBelongsToMany(A, 'as', 'id', 'id');

var a = new A({id: 'a1'});
a.bs = [new B({id: 'b1'})];
a.saveAll();

// Stash some extra fields on the link.
A_B.get('a1_b1').update({extra: '42'});

A.get('a1').getJoin({bs: true}).then(console.log);
// > {"id": "a1", "bs": [{"id": "b1"}] }
A.get('a1').getJoin({bs: {_merge: true}}).then(console.log);
// > {"id": "a1", "bs": [{"id": "b1", "extra": "42"}] }
```

This isn't necessarily the right way to implement this, but I wanted to open it for discussion. In particular, there isn't a sensible way to model the linking table without knowing the internals of `thinky`, and there is no support for saving documents merged in this way.

I think a better way to implement this functionality might be with [`hasMany..through`](http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association). Currently, `thinky` models `hasMany` relationships with an embedded array rather than a linking table, making that a bigger change than I had time for, but in theory it might look something like this:
```javascript
var A = thinky.createModel('A', {id: String});
var B = thinky.createModel('B', {id: String});
var Link = thinky.createModel('Link', {id: String, extra: String});
A.hasMany(B, 'bs', 'id', 'id', {through: Link});
B.hasMany(A, 'as', 'id', 'id', {through: Link});
```