I have 2 tables. 1 called events with an event ID and another table called tickets which I want to have primary keys of event ID and ticket ID. I am also using a PostgreSQL database. At the moment ,I have it as a foreign key but would like to have it as a primary key in the ticket table with the ticket 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');
});
A composite key is made by the combination of two or more columns in a table that can be used to uniquely identify each row in the table when the columns are combined uniqueness of a row is guaranteed, but when it is taken individually it does not guarantee uniqueness, or it can also be understood as a primary key made ...
No there is nothing wrong in linking two identical primary keys in different tables but the problem arises when the data type is declared as identity.
Connecting Knex with Postgres We specify the connection parameters for Postgres and point Knex to connect to the pg client. const db = require("knex")({ client: "pg", connection: { host: "localhost", user: "postgres", password: "", database: "knex-test" } }); app. set("db", db);
As per Knex's documentation here:
primary — column.primary([constraintName]); table.primary(columns, [constraintName]) When called on a single column it will set that column as the primary key for a table. If you need to create a composite primary key, call it on a table with an array of column names instead. Constraint name defaults to tablename_pkey unless constraintName is specified.
Therefore, in your case you could add:
table.primary(['name_of_column_1', 'name_of_column_2']);
Using your example I think you've got 2 options:
Option 1 (use the id as primary key and add a unique constraint):
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']);
});
Options 2 (Use the two ids as composite primary keys):
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']);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With