KnexJS外键约束中的种子表

时间:2019-02-20 13:23:23

标签: javascript postgresql knex.js

我正在构建NodeJS API后端,并使用Knex来处理数据库迁移等。

我有3个表:stallsmarketsbookings

在我的bookings表中,我想同时引用idstalls表中的markets列。

我已按照以下步骤设置了bookings迁移:-

    exports.up = function(knex, Promise) {
  return knex.schema.createTable("bookings", table => {
    table.increments("id");
    table.string("firstName");
    table.string("lastName");
    table.string("address");
    table.string("phoneNumber");
    table.string("emailAddress");
    table
      .integer("marketDateId")
      .references("id")
      .inTable("markets");
    table
      .integer("stallTypeId")
      .references("id")
      .inTable("stalls");
    table.boolean("clothesRail");
    table.string("businessName");
    table.boolean("businessInsurance");
    table.string("items");
  });
};

exports.down = function(knex, Promise) {
  return knex.schema.dropTable("bookings");
};

档位:

    exports.up = (knex, Promise) => {
  return knex.schema.createTable("stalls", table => {
    table.increments("id");
    table.string("stallType");
  });
};

exports.down = (knex, Promise) => {
  return knex.schema.dropTable("stalls");
};

市场:

exports.up = (knex, Promise) => {
  return knex.schema.createTable("markets", table => {
    table.increments("id");
    table.string("marketDate");
  });
};

exports.down = (knex, Promise) => {
  return knex.schema.dropTable("markets");
};

我已经为stallsmarkets表添加了一些虚拟数据,但是当我尝试使用以下种子文件为bookings表添加种子时:

bookings.js

exports.seed = (knex, Promise) =>
  knex("bookings")
    .del()
    .then(() =>
      knex("bookings").insert([
        {
          firstName: "Test",
          lastName: "Tester",
          phoneNumber: "07123 123456",
          emailAddress: "test@lb-dev.io",
          marketDateId: "7",
          stallTypeId: "7",
          clothesRail: false,
          items: "Testing Stuff"
        },
        {
          firstName: "Test",
          lastName: "Testington",
          phoneNumber: "07123 123456",
          emailAddress: "test@lb-dev.io",
          marketDateId: "8",
          stallTypeId: "8",
          clothesRail: false,
          businessName: "TestCrafts",
          items: "Testing Stuff"
        },
        {
          firstName: "Test",
          lastName: "Tester",
          phoneNumber: "07123 123456",
          emailAddress: "test@lb-dev.io",
          marketDateId: "9",
          stallTypeId: "9",
          clothesRail: true,
          businessName: "TestBusiness",
          businessInsurance: true,
          items: "Testing Stuff"
        }
      ])
    );

运行knex seed:run时出现以下错误

update or delete on table "markets" violates foreign key constraint "bookings_marketdateid_foreign" on table "bookings"

1 个答案:

答案 0 :(得分:0)

marketDateId表的bookings字段被定义为引用其他表中的字段的foreign key。这是为了确保参照完整性。有关示例,请参见相关的postgres tutorial page

因此,您的代码必须确保它仅尝试分配该其他表的一行中存在的marketDateId值。