Skip to content

Simplify associations #6091

Closed
Closed

Description

@overlookmotel

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:

  1. There are 3 kinds of associations: one-to-one, one-to-many and many-to-many.
  2. 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

  1. mickhansen commented on Jun 12, 2016

    @mickhansen
    Contributor

    There's an existing issue somewhere for automatically creating the inverse relations.

  2. felixfbecker commented on Jun 12, 2016

    @felixfbecker
    Contributor

    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:

    • hasOne and belongsTo is a matter of where the foreign key is created
    • hasMany and belongsTo are for 1:n relations
    • belongsToMany is for n:m

    One confusion point for me was why hasMany is not used for n:m relations.

  3. overlookmotel commented on Jun 12, 2016

    @overlookmotel
    ContributorAuthor

    @felixfbecker

    What I'm suggesting is that you define an association using a single statement, but it creates the association on both models.

    A.hasMany(B);
    expect(A.associations.B).to.be.ok;
    expect(B.associations.A).to.be.ok;

    Basically I propose retiring Model.belongsTo - because it'd be made redundant.

    one-to one

    A.hasOne( B );

    Or, if you want the foreign key on the other table:

    B.hasOne( A );

    Equivalent to current:

    A.hasOne( B );
    B.belongsTo( A );

    one-to-many

    A.hasMany( B );

    Equivalent to the current:

    A.hasMany( B );
    B.belongsTo( A );

    many-to-many

    A.hasManyMany( B );

    Equivalent to current:

    A.belongsToMany( B, { through: 'AB' } );
    B.belongsToMany( A, { through: 'AB' } );

    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.

  4. overlookmotel commented on Jun 12, 2016

    @overlookmotel
    ContributorAuthor

    @mickhansen The other issue about automatically creating both sides of an association is here: #5144

    I should have checked before posting...

  5. overlookmotel commented on Jun 12, 2016

    @overlookmotel
    ContributorAuthor

    I just realised that this might not work for association scopes. They're not always bi-directional are they?

  6. felixfbecker commented on Jun 12, 2016

    @felixfbecker
    Contributor

    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.

  7. felixfbecker commented on Jun 12, 2016

    @felixfbecker
    Contributor

    But hasManyMany() sounds super weird. Thats the only point I would improve - make hasMany() work for 1:n and n:m and decide on the association type based on if you pass through

  8. felixfbecker commented on Jun 12, 2016

    @felixfbecker
    Contributor

    Also, is the association object the same for belongsTo / hasMany? With your proposal, how would you get the association object?

  9. overlookmotel commented on Jun 12, 2016

    @overlookmotel
    ContributorAuthor

    @felixfbecker OK maybe hasManyMany() could be hasManyToMany() 😄

    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 because hasMany was 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...

    Band.Album = Band.hasMany( Album );
    Album.Band = Band.Album.reverse;

    i.e. each association has a reverse property which points to the association's pair (equivalent to Album.Band = Album.belongsTo( Band ))

  10. felixfbecker commented on Jun 12, 2016

    @felixfbecker
    Contributor
    Band.Album = Band.hasMany( Album );
    Album.Band = Band.Album.reverse;

    but thats so non symmetric... I prefer defining the association twice honestly

  11. overlookmotel commented on Jun 12, 2016

    @overlookmotel
    ContributorAuthor

    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.

  12. mickhansen commented on Jun 13, 2016

    @mickhansen
    Contributor

    One confusion point for me was why hasMany is not used for n:m relations.

    We did originally use 2 x hasMany for N:M but it was a huge headache to maintain.

  13. felixfbecker commented on Jun 13, 2016

    @felixfbecker
    Contributor

    @mickhansen But back then through wasn't required - you can now easily infer wether it is 1:n or n:m depending on wether through is set or not.

  14. mickhansen commented on Jun 13, 2016

    @mickhansen
    Contributor

    @felixfbecker Correct, that does help. I like explicit though, and it seems to be in tune with other ORMs in other languages.

  15. overlookmotel commented on Jun 13, 2016

    @overlookmotel
    ContributorAuthor

    A while back we discussed using through to make indirect associations which go via another association (#3935). Draft API was:

    User.hasOne( Profile );
    Profile.belongsTo( User );
    
    Profile.hasMany( Email );
    Email.Profile = Email.belongsTo( Profile );
    
    User.hasMany( Email, { through: Email.Profile } );

    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!

  16. mickhansen commented on Jun 13, 2016

    @mickhansen
    Contributor

    Ah yes, ideally i'd like to add pivot for N:M associations aswell (so the join models becomes the inner result between the source and the target)

  17. overlookmotel commented on Jun 13, 2016

    @overlookmotel
    ContributorAuthor

    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.

  18. overlookmotel commented on Jun 13, 2016

    @overlookmotel
    ContributorAuthor

    If we're not doing a full overhaul, I vote for keeping belongsToMany. Everyone had to switch hasMany to belongsToMany for Sequelize v3. It'll probably piss people off if they have to switch back again for v4!

  19. felixfbecker commented on Jun 13, 2016

    @felixfbecker
    Contributor

    @overlookmotel Yes, we should keep it, it is not worth the effort. But the docs should be cleaned up:
    image
    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.

  20. overlookmotel commented on Jun 13, 2016

    @overlookmotel
    ContributorAuthor
  21. added
    status: in discussion
    on Jun 23, 2016
  22. stale commented on Jun 29, 2017

    @stale

    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 🙂

  23. overlookmotel commented on Jun 29, 2017

    @overlookmotel
    ContributorAuthor

    Were the docs ever cleaned up as per @felixfbecker's suggestion?

  24. felixfbecker commented on Jun 29, 2017

    @felixfbecker
    Contributor
  25. overlookmotel commented on Jun 29, 2017

    @overlookmotel
    ContributorAuthor

    @felixfbecker So think this can be closed then?

  26. felixfbecker commented on Jun 29, 2017

    @felixfbecker
    Contributor

    You tell me, it's your issue 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: in discussion

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions