Search code examples
databasetypescriptpostgresqldatabase-designknex.js

On knex migration:up, table.foreign is not showing up on the actual table on the terminal


I have setup knex migration to create two tables

export async function up(knex: Knex): Promise<void> {

    const table1 = await knex.schema.hasTable('users');
    if (!table1) {
        await knex.schema.createTable('users', (table) => {
            table.increments("id").primary();
            table.string("username");
            table.string("email");
            table.string("password");
            table.string("role");
            table.timestamp("created_at");
            table.timestamp("updated_at");
            table.timestamp("logged_at");
        });
    }

    const table2 = await knex.schema.hasTable('usersloc');
    if (!table2) {
        await knex.schema.createTable('usersloc', (table) => {
            table.increments("locid");
            table.string("lat");
            table.string("lng")
            table.foreign("userid");
        });
    }
}

However, when I did a select * from usersloc;, userid in usersloc is nowhere to be found.

My intention is to have it referred to the id at the "users" table.

Any idea what happened?


Solution

  • Solution found - looks like the UUID needs to have a .unique() reference on both tables. My guess is that even though UUID may take billions of years to have 1% chance of collision, it is still not a unique ID, thus a .unique() reference is needed.