我正在构建NodeJS API后端,并使用Knex来处理数据库迁移等。
我有3个表:stalls
,markets
和bookings
在我的bookings
表中,我想同时引用id
和stalls
表中的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");
};
我已经为stalls
和markets
表添加了一些虚拟数据,但是当我尝试使用以下种子文件为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"
答案 0 :(得分:0)
marketDateId
表的bookings
字段被定义为引用其他表中的字段的foreign key。这是为了确保参照完整性。有关示例,请参见相关的postgres tutorial page。
因此,您的代码必须确保它仅尝试分配该其他表的一行中存在的marketDateId
值。