Skip to content

Support for belongsTo through #3845

Closed
Closed

Description

@verdier

Is there a plan for supporting bellongsTo.through such as:

A.hasMany(B)
A.hasMany(C) // Through B

B.belongsTo(A)
B.hasMany(D)

C.belongsTo(B);
C.belongsTo(A) // Through B

Activity

  1. janmeier commented on Jun 1, 2015

    @janmeier
    Member

    Through is only usefull for n:m which is handled by belongsToMany

  2. verdier commented on Jun 1, 2015

    @verdier
    ContributorAuthor

    @janmeier, why no for N:1 such as in my previous exemple, I need this in a real world exemple:

    Operations.belongsTo(User)
    Operations.hasMany(Breakdowns)
    
    /* There is no way to define this relation without adding a 
    field to the breakdown, but I will have to manually sync 
    operation.userId and breakdown.userId */
    Breakdowns.belongsTo(User) 
  3. janmeier commented on Jun 1, 2015

    @janmeier
    Member

    If there is always only a single entry on one side of the relation, why do you need a join table?

    Perhaps you can draw the relations, I can't really figure out your datamodel in my head :)

  4. mickhansen commented on Jun 1, 2015

    @mickhansen
    Contributor

    Scratch my previous comment.

    @verdier You are looking to fetch a relation via another relation? Rails support this i believe, we don't yet i'm afraid.

  5. verdier commented on Jun 1, 2015

    @verdier
    ContributorAuthor

    @mickhansen yep, the query would be something like that:

    ...from breakdowns, operations, users 
    where operations.id = breakdowns.operationId and users.id = operations.userId

    No problem, I have solution for now.

  6. verdier commented on Jun 1, 2015

    @verdier
    ContributorAuthor

    @janmeier the model is something like that:

    User -> Operation -> Breakdown
    

    A user have multiple operations, an operation have multiple breakdowns, but: a breakdown and an operation have only one same user. The operation works as a join table between one breakdown and one user.

    I now that I can store the userId in the breakdown AND in the operation but I will have to maintain the userId fields (ie operation.userId === breakdown.userId always).

    beforeCreate(breakdown) {
        if (!breakdown.operationId) throw new Error('Unable to create breakdown without operation.');
    
        /* Attach owner to breakdown. */
        if (!breakdown.ownerId) {
            return breakdown.getOperation().then(function(operation) {
                if (!operation || !operation.ownerId) throw new Error('Unable to retrieve owner from operation.');
                breakdown.ownerId = operation.ownerId;
            });
        }
    },
  7. mickhansen commented on Jun 1, 2015

    @mickhansen
    Contributor

    Or you can use a nested include.

  8. verdier commented on Jun 1, 2015

    @verdier
    ContributorAuthor

    @mickhansen yep, but that's mean that if you fetch the user's breakdown, you'll fetch, for each breakdown, the operation. That's not very efficient. Something like:

    {
     include: [{
     model: Operation,
     fetch: false, // Search for a condition in nested models, but do not eager load.
     where: {
      userId: userId
     }
    }

    would be very usefull.

    note: that's not so good when you have a breakdown instance and you need the user. You have to fetch the operation.

  9. mickhansen commented on Jun 1, 2015

    @mickhansen
    Contributor

    @verdier You'd need the join in any case.

  10. verdier commented on Jun 1, 2015

    @verdier
    ContributorAuthor

    @mickhansen are you open for a pull request to support this feature:

    Breakdowns.belongsTo(User, {
     through: Operation
    });

    note: I need a join, but without selecting any column of the operation model.

  11. mickhansen commented on Jun 1, 2015

    @mickhansen
    Contributor

    @verdier You can disable attributes on the join with include.attributes = [].
    Yes we'd be open to a pull request :)
    The argument to through should maybe be an Association rather than a Model, for less ambiguity, not sure.

  12. janmeier commented on Jun 1, 2015

    @janmeier
    Member

    Not sure through is even a good name here - it might be too confusing..

  13. mickhansen commented on Jun 1, 2015

    @mickhansen
    Contributor

    @janmeier Yeah i believe that's why Rails use through for this and pivot for our through.

  14. added
    type: feature
    on Oct 20, 2015
  15. 1 remaining item

  16. felixfbecker commented on Jun 13, 2016

    @felixfbecker
    Contributor

    @mickhansen I just find the name belongsToMany so confusing. The difference between hasMany and belongsToMany is not clear at all.
    n:m in other languages:

    • Ruby calls n:m relations has_and_belongs_to_many, that makes it more clear that it is basically hasMany, but both ways.
    • Doctrine (PHP) uses @hasMany on both models with mappedBy and inversedBy parameters. The join table is set through @JoinTable.
    • Hibernate uses many-to-many columns on both models that both specify the same join table name table

    I define my n:m relations in Sequelize in a similar way to the above:

    Project.ts

    export const Project = sequelize.define('Project', {...});
    
    import {User} from './User';
    export const ProjectParticipants = Project.belongsToMany(User, {as: 'participants', through: 'UserProjects'});

    User.ts

    export const User = sequelize.define('User', {...});
    
    import {Project} from './Project';
    export const UserProjects = User.belongsToMany(Project, {as: 'projects', through: 'UserProjects'});

    Usage

    import {User, UserProjects} from './User';
    const users = await User.find({include: [UserProjects]});

    Basically I supply through as the join table name. And imo this would be nicer API if I could use hasMany for this.

  17. mickhansen commented on Jun 13, 2016

    @mickhansen
    Contributor

    @felixfbecker We actually have hasAndBelongsToMany as an alias for belongsToMany.
    I understand your issue, but i don't think it's something we're likely to change right now, i prefer N:M being a seperate call from 1:M

  18. felixfbecker commented on Jun 13, 2016

    @felixfbecker
    Contributor

    @mickhansen did not know that, thanks! And I also think it's better to keep it, just wanted to share my thoughts.

  19. overlookmotel commented on Jun 13, 2016

    @overlookmotel
    Contributor

    If we think it's confusing, maybe make hasAndBelongsToMany the main name listed in the docs with belongsToMany as the alias, rather than the other way around?

  20. overlookmotel commented on Jun 13, 2016

    @overlookmotel
    Contributor

    On the subject of through, I feel that through should refer to the model name rather than the table name.

    Two reasons:

    1. With every other interface in Sequelize, you use model names, so this stands out as an anomaly.
    2. The over-arching principle of an ORM is to abstract away the database tables, so this breaks that principle.

    A small point perhaps, but I feel consistency is really important to get the "it just works" effect.

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

  22. heisian commented on Apr 12, 2018

    @heisian

    Have this issue as well. As a workaround my thoughts are:

    @verdier OP's example:

    • Give Operations a UNIQUE constraint on the breakdown_id
    • Any Breakdown can only be associated once (to Operation), effectively giving the Breakdown only one possible parent.
    • Add the helper for Breakdown:
    Breakdown.prototype.getUser = async function() {
      const [user] = await this.getUsers()
      return user
    }

    @felixfbecker's example:

    • Give UserProjects a UNIQUE constraint on the project_id
    • Any Project can only be associated once (to User), effectively giving the Breakdown only one possible parent.
    • Add the helper for Project:
    Project.prototype.getUser = async function() {
      const [user] = await this.getUsers()
      return user
    }

    And finally, for my glorious example:

    Referrers => Referral Programs => Referrals
    

    A Referrer can have any number of Referral Programs that can have any number of Referrals.
    A Referral can only belong to one Referral Program which can only belong to one Referrer.
    A Referral can only belong to one Referrer through a Referral Program.

    Referrrrrrrrrrrrrrrrrrr....

  23. hassanhe commented on Aug 27, 2018

    @hassanhe

    @verdier OK this magically ✨ work's for me, @mickhansen @janmeier could any of you please explain why maybe it's already implemented there and useful I've seen a lot of requests for that feature.
    even though the option through is not possible in belongsTo I've tried it and what makes it work that I've passed also foreignKey: 'id' which refers to the A FK in the join table C

    // A --> B --> C
    
    C.belongsTo(A, {
      through: B,
      foreignKey: 'id',
    })
    

    if this has no unexpected behavior, the next step is how do we assign even more far nested joins like it
    .ie

    // A --> B --> C --> D
    
    D.belongsTo(A, { 
      ... how ?
    })
    

    thank you ❤

  24. zocoi commented on Apr 24, 2019

    @zocoi

    @hassangit your example doesn't work for me, what do you do exactly?

  25. odravison commented on Sep 1, 2020

    @odravison

    I passed by a lot of problem because Sequelize doesn't support this feature. Would be very nice to have this on this project!
    It's very useful.

  26. simonbrent commented on Nov 10, 2020

    @simonbrent

    I have noticed that if you do

    var association = modelA.belongsToMany(modelB, { through: 'model_c', ... });
    association.isMultiAssociation  = false;
    association.isSingleAssociation = true;
    

    then you get back the associated data as a single item rather than an array, while the SQL query does not change.

  27. david-mart commented on Jan 24, 2021

    @david-mart

    I have noticed that if you do

    var association = modelA.belongsToMany(modelB, { through: 'model_c', ... });
    association.isMultiAssociation  = false;
    association.isSingleAssociation = true;
    

    then you get back the associated data as a single item rather than an array, while the SQL query does not change.

    this actually works, thank you for a tip!

  28. rdsedmundo commented on Nov 8, 2023

    @rdsedmundo

    @ephys @WikiRik do you think this could be re-opened? I believe it's still relevant and the stale bot closed it a while ago.

    I have another use case for this, which adds to what OP requested. I'm using an association scope and through an unique key I know that there's one only row that will satisfy it through the junction table, but I'd like to receive a single item instead of an array.

       // #1 scenario: a User has many Groups
        models.User.belongsToMany(models.Group, {
          foreignKey: 'userId',
          through: UserGroups,
        });
    
       // #2 scenario: but a User only owns a single personal group
        models.User.belongsToMany(models.Group, {
          as: 'primaryGroup',
          foreignKey: 'userId',
          scope: { 
            groupType: 'personal' 
          },
          through: {
            model: UserGroups,
            scope: {
              isGroupOwner: true,
            },
          },
        });
    

    I know I could probably just set that the User owns the Group elsewhere, but it's desirable to have it centralized it in the junction UserGroup table, as it's subject to change.

    The workaround provided by @simonbrent works, but it feels a bit hacky and I suppose this could change in future Sequelize versions since it seems to be overriding internal variables. (it actually did not work for me)

    This could also potentially come as an option in belongsToMany like isSingleRow or whatever.

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

    staletype: feature

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions