gpt4 book ai didi

node.js - Sequelize 中的复合主键

转载 作者:行者123 更新时间:2023-12-03 22:16:07 24 4
gpt4 key购买 nike

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

var relation = {
'user_id': {
type: DataTypes.INTEGER
},
'organization_id':{
type: DataTypes.INTEGER
}
}
我想定义一个主键,如 primary key (user_id, organization_id)注意:使用 PostgreSQL

最佳答案

您可以通过指定 primaryKey: true 在 Sequelize 中创建复合主键针对不止一栏。例如。

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)

关于node.js - Sequelize 中的复合主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59163675/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com