Skip to content

Indirect associations #3935

Open

Description

@overlookmotel

Sometimes models have relationships between them which rely on intermediate models.

Here's an example:

Data about users is split into two models User and Profile (with User containing core authentication info, and Profile containing more general public info about the user) and then a Profile can have several Email records associated with it.

var User = sequelize.define('user', {
    username: Sequelize.STRING(50),
    password: Sequelize.STRING(50)
} );
var Profile = sequelize.define('profile', {
    firstName: Sequelize.STRING(50),
    lastName: Sequelize.STRING(50)
} );
var Email = sequelize.define('email', {
    email: {
        type: Sequelize.STRING(200),
        unique: true
    }
} );

User.hasOne(Profile);
Profile.belongsTo(User);

Profile.hasMany(Email);
Email.belongsTo(Profile);

Now, if you want to get all the Emails for a User, you have to go through Profile:

User.find( {
    where: {id: 123},
    include: {
        model: Profile,
        include: Email
    }
} ).then( function(user) {
    var emails = user.profile.emails;
    // do something with emails
} );

It would be really useful if you could define the indirect association on the model with something like:

User.hasMany(Email, {
    through: {
        model: Profile,
        include: Email
    }
} );
Email.belongsTo(User, {
    through: {
        model: Profile,
        include: User
    }
} );

And then just do:

User.find( {
    where: {id: 123},
    include: Email
} ).then( function(user) {
    var emails = user.emails;
    // do something with emails
} );

or:

user.getEmails().then( function(emails) {
    // do something with emails
} );

This should also work for very complex associations through multiple join tables.

The intention is to:

  • Define relationships between models in the model definitions rather than in code which fetches those associations - which in my opinion is where they belong
  • Remove boiler-plate code every time you want to find() that association
  • Therefore make code more maintainable as you can switch around the underlying implementation of an association (e.g. changing the Profile to Email relationship to many-to-many) without having to change the code everywhere you fetch that association

My use case is that I'm building apps with a lot of complex nested relationships between models, and constantly find myself writing the same find({ include: ... }) code over and over again. It would be great to be able to cut that down.

Does anyone have any thoughts on this?

Activity

  1. added
    type: feature
    on Jun 15, 2015
  2. mickhansen commented on Jun 15, 2015

    @mickhansen
    Contributor

    That's actually a feature request that pops up now and again (some even expecting non-N:M relations to support through).

    However i might suggest using an association reference as the through argument:

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

    But i suppose we could trivially support both :)

  3. overlookmotel commented on Jun 15, 2015

    @overlookmotel
    ContributorAuthor

    @mickhansen Do you think this would be hard to implement? I don't know the innards of how through is dealt with inside Sequelize.

    Yes, supporting associations as the value of through could be very nice, as well as an include syntax.

  4. mickhansen commented on Jun 16, 2015

    @mickhansen
    Contributor

    We only support through for N:M.
    through for 1:1 or 1:M would work differently - I don't think it would be too tricky though.

  5. overlookmotel commented on Jun 16, 2015

    @overlookmotel
    ContributorAuthor

    I was thinking it would be great if it also supported nested relationships.

    Like: A Tour has many Concerts, a Concert has many Bands, a Band has many Musicians.

    Tour.hasMany(Concert);
    Concert.hasMany(Band);
    Band.hasMany(Musician);
    
    Tour.hasMany(Musician, {
        through: {
            model: Concert,
            include: {
                model: Band,
                include: Musician
            }
        }
    } );

    Then you could do:

    Tour.getMusicians().then( function (musicians) {
        // email musicians the tour schedule
    } );

    This kind of case is where the feature would really come into it's own, as it would cut out a huge amount of model.find( { include: ... } ) logic.

    Would that make it much more difficult to implement?

  6. overlookmotel commented on Jun 16, 2015

    @overlookmotel
    ContributorAuthor

    Or using associations, as you suggested:

    Tour.hasMany(Concert);
    Concert.hasMany(Band);
    Band.hasMany(Musician);
    
    Tour.hasMany(Band, { through: Tour.associations.concerts } );
    Tour.hasMany(Musician, { through: Tour.associations.bands } );
  7. mickhansen commented on Jun 16, 2015

    @mickhansen
    Contributor

    Hmm, i suppose you'd just need some recursive logic to build the join. However the syntax for defining a nested through model is not that clear imo.

  8. overlookmotel commented on Jun 17, 2015

    @overlookmotel
    ContributorAuthor

    @mickhansen Do you have another idea for the nested through model syntax?

    Maybe it'd be best only to support the association syntax, to keep it simple.

    model.hasMany( anotherModel, { through: association } )
  9. overlookmotel commented on Jun 13, 2016

    @overlookmotel
    ContributorAuthor

    Related issue: #3845

  10. 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 🙂

  11. overlookmotel commented on Jun 29, 2017

    @overlookmotel
    ContributorAuthor

    I'm still keen on implementing this at some point.

  12. JoshuaWise commented on Aug 14, 2017

    @JoshuaWise

    Is this issue being looked at? I'm trying to implement an indirect relationship but sequelize won't let me express my database design. It's too limited without indirect relationships

  13. mikefowler commented on Oct 2, 2017

    @mikefowler

    @mickhansen has any further thought been given to this? It seems that this is a pretty common type of relationship that those coming from Rails-land will expect to be possible. /cc @overlookmotel

  14. andrew-st-angelo-77media commented on Aug 22, 2018

    @andrew-st-angelo-77media

    I agree that this would be very useful. I use the same indirect/pass-through association in Rails, frequently. Further, if what you're interested is data associated with the secondary model, if would save bandwidth on a query to not have to pull down the intermediate model, as part of a Primary.find({ ... , include: { model: NonTrivialIntermediate, include: NeededModels }})

  15. stale commented on Jul 23, 2019

    @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 🙂

  16. added theissue type on Mar 9, 2025
  17. removed
    type: feature
    on Mar 9, 2025
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

    No labels
    No labels

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions