【问题标题】:Knex.js migrations with unique constraint function具有独特约束功能的 Knex.js 迁移
【发布时间】:2018-01-30 02:23:26
【问题描述】:

我目前正在尝试将一个新表迁移到我的数据库中。该表是用户表。这是我的代码:

exports.up = function(knex, Promise) {
  return knex.schema.createTableIfNotExists('users', function(table) {
    table.increments('id').primary();
    table.string('first_name').notNullable();
    table.string('last_name').notNullable();
    table.string('email').unique().notNullable();
    table.string('password').notNullable();
    table.timestamps(false, true);
  }).then(() => {
    console.log('Users Table is Created!');
  })
};

exports.down = function(knex, Promies) {
  return knex.schema.dropTable('users')
    .then(() => {
      console.log('Users Table has been Dropped!');
    })
};

这会返回两个错误:

Knex:warning - migrations failed with error: alter tableusersadd uniqueusers_email_unique(email) - Key column 'email' doesn't exist in table

Error: Key column 'email' doesn't exist in table

看来unique() 正在尝试在我尝试创建的表上执行更改表。因此电子邮件列不存在的错误。我在这里做错了什么,还是在创建表时不能对列执行unique() 函数?我在文档的 createTable 中看到了使用 unique() 函数的示例。所以我不知道为什么这会以所述错误响应。

我的数据库正在创建中,我可以看到它。似乎unique() 约束并未应用于未创建的电子邮件列。

【问题讨论】:

    标签: mysql api express migration knex.js


    【解决方案1】:
    knex.schema.createTableIfNotExists('users', function(table) {
        table.increments('id').primary();
        table.string('first_name').notNullable();
        table.string('last_name').notNullable();
        table.string('email').unique().notNullable();
        table.string('password').notNullable();
        table.timestamps(false, true);
      }).toSQL().forEach(query => console.log(query.sql))
    

    创建以下 SQL

    create table if not exists "users" ("id" serial primary key, "first_name" varchar(255) not null, "last_name" varchar(255) not null, "email" varchar(255) not null, "password" varchar(255) not null, "created_at" timestamptz not null default CURRENT_TIMESTAMP, "updated_at" timestamptz not null default CURRENT_TIMESTAMP);
    alter table "users" add constraint "users_email_unique" unique ("email");
    

    因此,如果表已经具有该名称的约束,则创建约束的查询将失败。但是您的错误似乎确实涉及其他一些奇怪的情况。

    【讨论】:

      【解决方案2】:

      所以事实证明我需要删除所有表并重新运行我的迁移。这就是为什么它不起作用以及为什么我认为它试图执行alter table

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-05
        • 2022-06-14
        • 2012-03-29
        • 2015-05-25
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        • 1970-01-01
        相关资源
        最近更新 更多