node.js - Sequelize 中的复合主键
问题描述
有人可以建议我如何在同一个表中的两列上设置主键。
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)
推荐阅读
- python-requests - Python-如何解决【WinError 10061】No connection could be made because the target machine主动拒绝
- php - POST请求上的laravel 7 api CSRF令牌不匹配
- vb.net - vb.net 构造后触发
- javascript - 我无法将表单输入中的数据添加到 Firestore 集合中,也无法找出问题所在
- python - 带有字符串和整数的递归函数
- python - Python添加文本和合并视频文件
- python - 2 个已处理的共享内存(应用程序崩溃)
- javascript - 将颜色转换为图像?
- javascript - 无法从发出的事件接收有效负载 - Socket.io
- python - 尝试发送列表 Discord.py 中的项目时出错