Repository navigation
Description
The difficulty I've had in #6023 with confusion over as and foreign keys made me start thinking about associations more generally.
I have to say I've always found the way associations work in Sequelize confusing as hell. It's the one part of the API which I make mistakes with time and time again. In fact I built a Sequelize plugin sequelize-definer so I didn't have to deal with defining associations directly because I always got it wrong!
I'd like to float the idea of a different way of defining associations in Sequelize.
Here's how I see it:
- There are 3 kinds of associations: one-to-one, one-to-many and many-to-many.
- In every one of these, the association is always bi-directional.
There's no such thing as a one-way association. You can't be my father unless I am your child. If I play for your football team, your team has me as a player.
I've often wondered, therefore, why you have to use two commands to create a single association. e.g.:
A.hasMany(B);
B.belongsTo(A);B.belongsTo(A) is already implied by A.hasMany(B).
Wouldn't it be more efficient and comprehensible if any bilateral association could be created with a single command? And that single command creates an association on both the source and target?
So...
Band.hasMany(Album);
var theBeetles = yield Band.findById(1);
var beetlesAlbums = yield theBeetles.getAlbums();
var sergeantPepper = yield Album.findById(1);
theBeetles = yield sergeantPepper.getBand();For all three types of association:
A.hasOne(B); // one-to-one
C.hasMany(D); // one-to-many
E.hasManyMany(F); // many-to-many
// with aliasing
A.hasMany(B, { as: 'BB', asReverse: 'AA' } );
// with foreign keys
A.hasManyMany(B, { foreignKey: 'A_ID', otherKey: 'B_ID' } );Maybe this is a silly idea, and it'd be a big breaking change. But what do you think?
It would certainly help to simplify the associations code which has to do a bit of jiggery-pokery to try to match up a belongsTo and hasMany into a pair, and might make associations in general less confusing.
Activity
mickhansen commentedon Jun 12, 2016
There's an existing issue somewhere for automatically creating the inverse relations.
felixfbecker commentedon Jun 12, 2016
It is true that it is a bit redundant to define the association twice as the relation is symmetric in the relational database. But from an ORM perspective it makes sense. Both models need to know that they are in some way associated with another.
It is of course a bit confusing that there are more than three association methods, but once you got the hang out of it, it makes sense:
hasOneandbelongsTois a matter of where the foreign key is createdhasManyandbelongsToare for 1:n relationsbelongsToManyis for n:mOne confusion point for me was why
hasManyis not used for n:m relations.overlookmotel commentedon Jun 12, 2016
@felixfbecker
What I'm suggesting is that you define an association using a single statement, but it creates the association on both models.
Basically I propose retiring
Model.belongsTo- because it'd be made redundant.one-to one
Or, if you want the foreign key on the other table:
Equivalent to current:
one-to-many
Equivalent to the current:
many-to-many
Equivalent to current:
NB because it knows everything it needs to know from the one statement, it'd no longer be necessary to provide
through(this is required at present to tie together the 2 statements).In general
The confusion I find isn't so much that's there's 4 command for 3 types of relationships. It's the stuff with foreign keys being to my mind "the wrong way around" and other oddities I've discussed in #6023 (comment)
Maybe best to see how that turns out before coming back to this.
overlookmotel commentedon Jun 12, 2016
@mickhansen The other issue about automatically creating both sides of an association is here: #5144
I should have checked before posting...
overlookmotel commentedon Jun 12, 2016
I just realised that this might not work for association scopes. They're not always bi-directional are they?
felixfbecker commentedon Jun 12, 2016
I don't dislike defining the association twice, when you have one file per model it is helpful to have the association defined in both.
felixfbecker commentedon Jun 12, 2016
But
hasManyMany()sounds super weird. Thats the only point I would improve - makehasMany()work for 1:n and n:m and decide on the association type based on if you passthroughfelixfbecker commentedon Jun 12, 2016
Also, is the association object the same for
belongsTo/hasMany? With your proposal, how would you get the association object?overlookmotel commentedon Jun 12, 2016
@felixfbecker OK maybe
hasManyMany()could behasManyToMany()😄If I remember right, a many-to-many relationship used to be defined with a pair of
hasMany()statements. I don't know why it changed - I imagine becausehasManywas then doing double-duty for both one-to-many and many-to-many relationships. And I think the code which figures out how to match up each pair of statements was getting over-complicated.Accessing the association object: I guess solution would be something like this...
i.e. each association has a
reverseproperty which points to the association's pair (equivalent toAlbum.Band = Album.belongsTo( Band ))felixfbecker commentedon Jun 12, 2016
but thats so non symmetric... I prefer defining the association twice honestly
overlookmotel commentedon Jun 12, 2016
To be honest, I'm not 100% sure this is best solution either. But what I do think is that the way it is now is damn confusing.
See here: #6023 (comment)
The thing about foreign keys being the "wrong way round" is particularly unintuitive.
mickhansen commentedon Jun 13, 2016
We did originally use
2 x hasManyforN:Mbut it was a huge headache to maintain.felixfbecker commentedon Jun 13, 2016
@mickhansen But back then
throughwasn't required - you can now easily infer wether it is 1:n or n:m depending on wetherthroughis set or not.mickhansen commentedon Jun 13, 2016
@felixfbecker Correct, that does help. I like explicit though, and it seems to be in tune with other ORMs in other languages.
overlookmotel commentedon Jun 13, 2016
A while back we discussed using
throughto make indirect associations which go via another association (#3935). Draft API was:If any changes are made which depend on the use of
through, it'd be nice if they didn't make the above impossible. (I still hope to implement this one day)PS there are 666 issues open on sequelize. The time of the beast is upon us!
mickhansen commentedon Jun 13, 2016
Ah yes, ideally i'd like to add
pivotfor N:M associations aswell (so the join models becomes the inner result between the source and the target)overlookmotel commentedon Jun 13, 2016
Are you talking about this #3845? Yeah, that sounds great. That's pretty much the same as I was talking about, but extended to many-to-many.
overlookmotel commentedon Jun 13, 2016
If we're not doing a full overhaul, I vote for keeping
belongsToMany. Everyone had to switchhasManytobelongsToManyfor Sequelize v3. It'll probably piss people off if they have to switch back again for v4!felixfbecker commentedon Jun 13, 2016
@overlookmotel Yes, we should keep it, it is not worth the effort. But the docs should be cleaned up:

There should only be three main sections: 1:1, 1:n and n:m that show how to define those relations. Don't make a headline
belongsToMany associations, it is confusing imo.overlookmotel commentedon Jun 13, 2016
Agreed @felixfbecker!
stale commentedon Jun 29, 2017
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If this is still an issue, just leave a comment 🙂
overlookmotel commentedon Jun 29, 2017
Were the docs ever cleaned up as per @felixfbecker's suggestion?
felixfbecker commentedon Jun 29, 2017
New docs are a lot better because they detect the header level:
http://docs.sequelizejs.com/manual/tutorial/associations.html
overlookmotel commentedon Jun 29, 2017
@felixfbecker So think this can be closed then?
felixfbecker commentedon Jun 29, 2017
You tell me, it's your issue 😄