Cod*_*234 11 postgresql composite-primary-key knex.js
我有2张桌子。1 调用带有事件 ID 的事件和另一个称为票证的表,我希望它具有事件 ID 和票证 ID 的主键。我也在使用 PostgreSQL 数据库。目前,我将它作为外键,但希望将它作为带有票证 ID 的票证表中的主键。
knex.schema.createTable('events', function (table) {
table.increments('id');
table.string('eventName');
});
knex.schema.createTable('tickets', function (table) {
table.increments('id');
table.string('ticketName');
table.foreign('tickets').references('events_id').inTable('events');
});
Run Code Online (Sandbox Code Playgroud)
Yaz*_*leh 18
根据此处的Knex 文档:
主要 — column.primary([constraintName]); table.primary(columns, [constraintName]) 当在单个列上调用时,它将将该列设置为表的主键。如果您需要创建复合主键,请改为在具有列名数组的表上调用它。除非指定了约束名称,否则约束名称默认为 tablename_pkey。
因此,在您的情况下,您可以添加:
table.primary(['name_of_column_1', 'name_of_column_2']);
Run Code Online (Sandbox Code Playgroud)
使用您的示例,我认为您有两个选择:
选项 1(使用 id 作为主键并添加唯一约束):
knex.schema.createTable('events', function (table) {
table.increments('id').primary();
table.string('eventName');
});
knex.schema.createTable('tickets', function (table) {
table.increments('id').primary();
table.string('ticketName');
table.integer('event_id').references('id').inTable('events');
table.unique(['id', 'event_id']);
});
Run Code Online (Sandbox Code Playgroud)
选项 2(使用两个 id 作为复合主键):
knex.schema.createTable('events', function (table) {
table.increments('id').primary();
table.string('eventName');
});
knex.schema.createTable('tickets', function (table) {
table.increments('id');
table.string('ticketName');
table.integer('event_id').references('id').inTable('events');
table.primary(['id', 'event_id']);
});
Run Code Online (Sandbox Code Playgroud)