Composite primary key in Sequelize
Asked Answered
P

1

24

Can someone suggest how do I set primary key on two columns within the same table.

var relation = {
        'user_id': {
            type: DataTypes.INTEGER
        },
        'organization_id':{
            type: DataTypes.INTEGER
        }
}

I want to define a primary key like primary key (user_id, organization_id)

Note: Using PostgreSQL

Pulsar answered 3/12, 2019 at 18:58 Comment(0)
V
32

You can create composite primary keys in Sequelize by specifying primaryKey: true against more than one column. E.g.

import { sequelize } from '../../db';
import { Model, DataTypes } from 'sequelize';

class Tbl extends Model {}
Tbl.init(
  {
    user_id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
    },
    organization_id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
    },
  },
  { sequelize, modelName: 'tbls' },
);

(async function test() {
  try {
    await sequelize.sync({ force: true });
  } catch (error) {
    console.log(error);
  } finally {
    await sequelize.close();
  }
})();

The execution result and generated SQL:

Executing (default): CREATE TABLE IF NOT EXISTS "tbls" ("user_id" INTEGER , "organization_id" INTEGER , PRIMARY KEY ("user_id","organization_id"))

Check the table definition:

=# \d+ tbls;
                             Table "public.tbls"
     Column      |  Type   | Modifiers | Storage | Stats target | Description
-----------------+---------+-----------+---------+--------------+-------------
 user_id         | integer | not null  | plain   |              |
 organization_id | integer | not null  | plain   |              |
Indexes:
    "tbls_pkey" PRIMARY KEY, btree (user_id, organization_id)
Various answered 19/3, 2020 at 5:38 Comment(3)
how can we associate a table to this composite key.Zippy
lol, this is the actual question @kailash yogeshwar. I tried ,but nothing is working.Harlene
I think you guys should read a bit of Database design. Specifically the kind of relationships between tables. More specifically, the many-to-many relationship and its usage cases.Disorder

© 2022 - 2024 — McMap. All rights reserved.