您可以通过指定在 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)