[英]Composite primary key in Sequelize
有人可以建議我如何在同一個表中的兩列上設置主鍵。
var relation = {
'user_id': {
type: DataTypes.INTEGER
},
'organization_id':{
type: DataTypes.INTEGER
}
}
我想定義一個像primary key (user_id, organization_id)
這樣的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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.