【问题标题】:Composite primary key in SequelizeSequelize 中的复合主键
【发布时间】:2020-03-28 12:39:10
【问题描述】:

有人可以建议我如何在同一个表中的两列上设置主键。

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

我想定义一个像 primary key (user_id, organization_id)这样的主键

注意:使用PostgreSQL

【问题讨论】:

    标签: node.js postgresql sequelize.js sequelize-cli


    【解决方案1】:

    您可以在 Sequelize 中创建复合主键,方法是针对多个列指定 primaryKey: true。例如

    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();
      }
    })();
    

    执行结果和生成的SQL:

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

    检查表定义:

    =# \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)
    

    【讨论】:

    • 我们如何将一个表关联到这个复合键。
    • 大声笑,这是@kailash yogeshwar 的实际问题。我试过了,但没有任何效果。
    猜你喜欢
    • 2021-02-01
    • 2016-08-21
    • 2018-08-26
    • 1970-01-01
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 2015-04-27
    相关资源
    最近更新 更多