Knex 在迁移中创建链表

时间:2021-04-29 15:50:20

标签: javascript knex.js

我有以下迁移代码:

exports.up = function(knex) {
    return knex.schema.createTable('users', function(table){
        table.increments();
        table.string('email', 100).unique().notNullable();
        table.string('password').notNullable();
      })
      .createTable('posts', function(table){
        table.increments();
        table.string('title').notNullable();
        table.string('content').notNullable();
        table.timestamp('created_at').defaultTo(knex.fn.now());

        table.int('userId').notNullable().references('id').inTable('users');
      })
      .createTable('comments', function(table){
        table.increments();
        table.string('content').notNullable();
        table.timestamp('created_at').defaultTo(knex.fn.now());
        
        table.int('userId').notNullable().references('id').inTable('users');
        table.int('postId').notNullable().references('id').inTable('posts');
      })
};

exports.down = function(knex) {
  return knex.schema.dropTable('users')
  .dropTable('posts')
  .dropTable('comments');
};

它产生以下错误:

migration failed with error: create table "posts" ("id" serial primary key, "title" varchar(255) not null, "content" varchar(255) not null, "created_at" timestamptz default CURRENT_TIMESTAMP, "userId" undefined not null) - type "undefined" does not exist

似乎很难连接用户和帖子表,但我不确定为什么。

1 个答案:

答案 0 :(得分:0)

想通了。

在这里,而不是 int

    table.int('userId').notNullable().references('id').inTable('users');

它应该是整数。

    table.integer('userId').notNullable().references('id').inTable('users');