question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How do I define a composite unique constraint using a association's foreign key?

See original GitHub issue

How do I define a composite unique constraint using a association’s foreign key?

From the docs, I have:

To get full control over the foreign key column added by sequelize, you can use the foreignKey option. It can either be a string, that specifies the name, or and object type definition,
equivalent to those passed to sequelize.define.

My model definition:

module.exports = function(sequelize, DataTypes) {
  var SelectedItem = sequelize.define('SelectedItem', {
    name: {
      type: DataTypes.STRING,
      allowNull: false
    },
    externalId: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: 'uniqueSelectedItem'
    },
    source: {
      type: DataTypes.ENUM('GOOGLE', 'YAHOO'),
      allowNull: false,
      unique: 'uniqueSelectedItem'
    }
  }, {
    paranoid: true,
    classMethods: {
      associate: function(models) {
        SelectedItem.belongsTo(models.Item, {
          foreignKey: {
            name: 'itemId',
            unique: 'uniqueSelectedItem'
          }
        });
      }
    }
  });

  return SelectedItem;
};

From the above definition, I have a composite unique constraint on fields externalId, source and itemId (foreign key for my SelectedItem.belongsTo(models.Item) relationship).

But here are the queries executed:

DROP TABLE IF EXISTS "SelectedItems" CASCADE;
DROP TYPE IF EXISTS "enum_SelectedItems_source";
SELECT t.typname enum_name, array_agg(e.enumlabel) enum_value FROM pg_type t JOIN pg_enum e ON t.oid = e.enumtypid JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace WHERE n.nspname = 'public'  AND t.typname='enum_SelectedItems_source'  GROUP BY 1
DROP TYPE IF EXISTS "enum_SelectedItems_source"; CREATE TYPE "enum_SelectedItems_source" AS ENUM('GOOGLE', 'YAHOO');
CREATE TABLE IF NOT EXISTS "SelectedItems" ("id"   SERIAL , "name" VARCHAR(255) NOT NULL, "externalId" VARCHAR(255) NOT NULL, "source" "enum_SelectedItems_source" NOT NULL, "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL, "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL, "deletedAt" TIMESTAMP WITH TIME ZONE, "itemId" INTEGER REFERENCES "Items" ("id") ON DELETE CASCADE ON UPDATE CASCADE, UNIQUE ("externalId", "source"), PRIMARY KEY ("id"));

Am I doing something wrong?

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Reactions:7
  • Comments:16 (13 by maintainers)

github_iconTop GitHub Comments

1reaction
janmeiercommented, Apr 7, 2015

As a temp. solution you could add the itemId could to the model, and in the association do: SelectedItem.belongsTo(models.Item, { foreignKey: SelectedItem.rawAttributes.itemIt });

0reactions
janmeiercommented, Jun 29, 2016

@OKNoah Please provide a SSCCE

Read more comments on GitHub >

github_iconTop Results From Across the Web

How can I make a composite unique constraint with foreign ...
You can use migrations for this. Sequelize-cli provides a methods addConstraint and andIndex which can be used to achieve. From the docs
Read more >
UNIQUE Constraints
A composite foreign key is a foreign key made up of a combination of columns. A composite foreign key can contain as many...
Read more >
When to use unique composite keys? [closed]
A database designer must define one or more composite KEYs whenever each row of the table under consideration has to be uniquely differentiated ......
Read more >
Composite and Foreign Keys as Primary Key
Composite and Foreign Keys as Primary Key · General Considerations​ · Primitive Types only​ · Identity through foreign Entities​ · Use-Case 1: Dynamic...
Read more >
Interface ThroughOptions<ThroughModel>
If true a unique constraint will be added on the foreign key pair. If set to a string, the generated unique key will...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found