Skip to content

Composite foreign keys #311

Open

Description

@Zerzio

Hi,

I found some posts about composite keys and relations but nothing is in the documentation and it doesn't seem to be supported (no relevant test cases)
Is this supported: Entity.hasMany(Other , {foreignKey: ['key1', ' key2', ' key3']});

Thanks,

Serge

Activity

  1. sdepold commented on Nov 4, 2012

    @sdepold
    Member

    nope. i'm sorry :)

  2. Zerzio commented on Nov 4, 2012

    @Zerzio
    Author

    I'm too ;-)
    I found those:

    Without it I guess I have to implement some instanceMethods flavour, right?
    The custom get method would use attributes of the object to fetch associated entities.
    Another suggestion before I start doing so?

  3. pilsy commented on Mar 2, 2013

    @pilsy

    Hi i was wondering if the code mentioned by Zerzio has been merged in yet? i couldn't see it anywhere

  4. sdepold commented on Mar 2, 2013

    @sdepold
    Member

    ahm. nope.

  5. janmeier commented on Mar 3, 2013

    @janmeier
    Member

    The innofluence fork is me and mickhansen. But the support is not yet complete, and we have agree not to fully implement it sequelize fully supports non-id primary keys. That is sometime in 1.7

  6. Domiii commented on Jul 23, 2014

    @Domiii
    Contributor

    Any updates on this issue yet? I currently need support for composite foreign keys. I guess, the best alternative is to simply impose a unique index on the composite key and use an auto-increment primary key instead?

  7. mickhansen commented on Jul 23, 2014

    @mickhansen
    Contributor

    @Domiii No work has been done as of yet. That is your best alternative yes, personally i think that's the best solution always but that's just me.

  8. Domiii commented on Jul 23, 2014

    @Domiii
    Contributor

    In that case, let me share my index-creating code here for other people running into the same problem. I only tested this with MySQL. It might need some fixing for other SQL formats.

    Example usage:

    var defaultOptions = {};
    // ....
    createIndexIfNotExists('some_table', ['column1', 'column2, ...], { indexOptions: 'UNIQUE'}, function(err) { if (err) ... else ... });
    

    Code:

    function createIndexIfNotExists(table, columns, options, cb) {
        if (typeof columns === 'string') columns = [columns];
        var indexName = (options && options.indexName) || table + '_' + columns.join('_');
    
        // check if index exists
        // see: http://stackoverflow.com/questions/2480148/how-can-i-employ-if-exists-for-creating-or-dropping-an-index-in-mysql
        var checkIndexSql = 'SHOW INDEX FROM ' + table + ' WHERE KEY_NAME = \'' + indexName + '\'';
        sequelize.query(checkIndexSql, null, defaultOptions).complete(function(err, res) {
            if (err) {
                cb(new Error("Unable to query index for table `" + table + "` - " + err.message));
                return;
            }
            if (res.length == 0) {
                // index does not exist yet
    
                // disable logging
                if (options) options.logging = nothing;
                else options = defaultOptions;
    
                // add index
                // see: https://github.com/sequelize/sequelize/blob/eb034333160867cf21251e51a08057985e1a5c77/lib/dialects/mysql/query-generator.js#L259
                var sql = "CREATE " + (options.indexOptions || "") + " INDEX " + indexName + 
                    (options.indexType ? (' USING ' + options.indexType) : "") +
                    " ON " + table + ' (' + columns.join(', ') + ')' +
                    (options.parser ? " WITH PARSER " + options.parser : "");
    
                sequelize.query(sql, null, defaultOptions).complete(function(err) {
                    if (err) {
                        cb(new Error("Unable to create index for table `" + table + "` - " + err.message));
                    }
                    else {
                        cb();
                    }
                });
            }
            else {
                cb();
            }
        });
    }
    
  9. changed the title [-]hasMany using mutiple foreign keys[/-] [+]Composite foreign keys[/+] on Apr 27, 2015
  10. kopertop commented on Oct 1, 2015

    @kopertop

    I just ran into this problem. Is there still no plan to support multi-column indexes on relations? Is there any workaround known other then using a single key index?

    Specifically, I'm trying to use the "findAll" with an "include" filter.

  11. mickhansen commented on Oct 1, 2015

    @mickhansen
    Contributor

    @kopertop There's a difference between indexes and constraints, we support multi column indexes on all tables.

  12. ivanjd commented on Oct 5, 2015

    @ivanjd

    That feature would be super helpful.

  13. jamesaspence commented on Oct 16, 2015

    @jamesaspence

    +1 I just ran into this as well, would make my job way easier. For now I guess I'm editing the table structure :/

  14. ozum commented on Dec 12, 2015

    @ozum
    Contributor

    👍

  15. mickhansen commented on Dec 15, 2015

    @mickhansen
    Contributor

    For everyone +1'ing this, are you looking to reference tables with multiple primary keys or what are the usecases here exacttly?

  16. 114 remaining items

  17. ryanwaite28 commented on Mar 1, 2023

    @ryanwaite28

    Okay, so developers want something like this?

    ModelA.hasMany(ModelB, {
      as: 'relationsB',
      keyMappings: [{ foreignKey: 'fk_1', sourceKey: 'pk_1' }, { foreignKey: 'fk_2', sourceKey: 'pk_2' }] 
    });
    
    ModelB.belongsTo(ModelA, {
      as: 'relationA',
      keyMappings: [{ foreignKey: 'fk_1', targetKey: 'pk_1' }, { foreignKey: 'fk_2', targetKey: 'pk_2' }] 
    });
  18. peralva commented on Mar 9, 2023

    @peralva

    Okay, so developers want something like this?

    ModelA.hasMany(ModelB, {
      as: 'relationsB',
      keyMappings: [{ foreignKey: 'fk_1', sourceKey: 'pk_1' }, { foreignKey: 'fk_2', sourceKey: 'pk_2' }] 
    });
    
    ModelB.belongsTo(ModelA, {
      as: 'relationA',
      keyMappings: [{ foreignKey: 'fk_1', targetKey: 'pk_1' }, { foreignKey: 'fk_2', targetKey: 'pk_2' }] 
    });

    It would be great

  19. linokriza commented on May 9, 2023

    @linokriza

    Any updates on this issue?

  20. ephys commented on Jun 21, 2023

    @ephys
    Member

    I'd call the option keys but otherwise it does seem to be like it's the only possible/acceptable design

  21. rabahmilano commented on Aug 10, 2023

    @rabahmilano

    Okay, so developers want something like this?

    ModelA.hasMany(ModelB, {
      as: 'relationsB',
      keyMappings: [{ foreignKey: 'fk_1', sourceKey: 'pk_1' }, { foreignKey: 'fk_2', sourceKey: 'pk_2' }] 
    });
    
    ModelB.belongsTo(ModelA, {
      as: 'relationA',
      keyMappings: [{ foreignKey: 'fk_1', targetKey: 'pk_1' }, { foreignKey: 'fk_2', targetKey: 'pk_2' }] 
    });

    does this syntaxe works with V6 ?

  22. Skryabind commented on Aug 20, 2023

    @Skryabind

    does anyone have this working for more complex queries? e.g. nested eager loading? in a case where ZoneDefinition is zoneGroup->zoneDefinitions because it's nested in an include?

    @jayenashar have you found a solution for nested eager loading?

  23. jayenashar commented on Aug 20, 2023

    @jayenashar

    @jayenashar have you found a solution for nested eager loading?

    i did but oh god it is so hacky. you may be better off making the full sql query manually.

    Outcome.hasOne(OutcomeTime, {
      as: "first",
      foreignKey: "outcomeID",
      scope: {
        // this doesn't work for the nested query as the table has an alias
        // createdAt: Sequelize.col('Outcome.firstTime')
        createdAt: Sequelize.where(
          Sequelize.col("offers->outcomes.firstTime"),
          "=",
          Sequelize.col("offers->outcomes->first.createdAt")
        ),
      },
    });
  24. KaKi87 commented on Jan 7, 2024

    @KaKi87

    I wonder, is there any other NodeJS ORM that has this feature ?

  25. piotr-pawlowski commented on Jan 9, 2024

    @piotr-pawlowski

    I wonder, is there any other NodeJS ORM that has this feature ?

    TypeORM, but there are other annoying issues

  26. sergioshev commented on Jan 9, 2024

    @sergioshev

    Damn, I made whole project using sequelize, everything is working fine, just one issue requires composite keys, now I am stuck.

    Are you working with the latest version? There is v7, may be they added some logic for this use case. I know they added new features like transaction handling etc.

  27. WikiRik commented on Jan 31, 2024

    @WikiRik
    Member

    @ephys not sure if you looked into this before, but @papandreou is interested in this feature. What I could piece together from earlier comments here is that we want support for them in associations with this as proposed API (based on a comment of about a year ago, not sure if we updated associations already back then);

    ModelA.hasMany(ModelB, {
      as: 'relationsB',
      keys: [{ foreignKey: 'fk_1', sourceKey: 'pk_1' }, { foreignKey: 'fk_2', sourceKey: 'pk_2' }] 
    });
    
    ModelB.belongsTo(ModelA, {
      as: 'relationA',
      keys: [{ foreignKey: 'fk_1', targetKey: 'pk_1' }, { foreignKey: 'fk_2', targetKey: 'pk_2' }] 
    });
    

    Do you have any idea how difficult this is to implement in v7?

  28. ephys commented on Feb 2, 2024

    @ephys
    Member

    I don't think it would be that difficult, but it's also not a super simple PR. You'd basically need to:

    • Update the option normalization logic to turn foreignKey and targetKey into keys, and make sure both are not used at the same time
    • Expose a keys property
    • Rewrite the targetKey and foreignKey and other related fields (not options!) on association classes to make them retrieve the value from keys instead, and make them throw if keys.length > 1.
    • Support inferring keys from composite Primary Keys.
    • Update all places that use targetKey or foreignKey and other related fields in our codebase to make them use the new keys property instead.

    Also, we could also consider naming keys -> foreignKeys and having the object keys be source and target:

    ModelB.belongsTo(ModelA, {
      as: 'relationA',
      foreignKeys: [{ source: 'fk_1', target: 'pk_1' }, { source: 'fk_2', target: 'pk_2' }] 
    });
    

    source and target being context-sensitive. In belongsTo, source is the FK owner. In hasOne, source is the PK owner. That's already what happens with sourceKey and targetKey today: source is always the model on which the method was called, and target is always the parameter.


    We also need an API design for belongsToMany:

    ModelB.belongsToMany(ModelA, {
      foreignKeys: [{ 
        source: 'pk_1', // name of attribute on ModalB
        target: 'pk_2', // name of attribute on ModalA
        sourceFk: 'fk_1', // name of FK on through -> source, points at `source` key
        targetFk: 'fk_2', // name of FK on through -> target, points at `target` key
      }],
    });
    

    Names are not perfect but suggestions are welcome. We could have something more explicit like throughToSource and throughToTarget

  29. added theissue type on Mar 9, 2025
  30. removed
    type: feature
    on Mar 9, 2025
  31. Harshil-Modi commented on Apr 10, 2025

    @Harshil-Modi

    If you're trying to join models using composite keys with Sequelize's include, make sure to use the on attribute with literal() to define the custom join condition manually:

    await ModelA.findAll({
      include: {
        model: ModelB,
        on: literal(
          `"ModelA"."pk_1" = "ModelB"."pk_1" AND "ModelA"."pk_2" = "ModelB"."pk_2"`
        ),
      },
    });
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

    existing workaroundhard

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions