gpt4 book ai didi

javascript - Postgres/Knex "insert or update on table "位置“违反外键约束”

转载 作者:行者123 更新时间:2023-11-29 12:35:47 25 4
gpt4 key购买 nike

当我尝试在 Knex 和 Postgres 中运行种子时,我继续遇到同样的错误。错误是 error: insert or update on table "locations"violates foreign key constraint "locations_user_id_fore
ign"
。有人能弄清楚为什么会抛出这个错误吗?我已经尝试更改了很多东西。谢谢!

用户迁移

exports.up = function(knex, Promise) {
return knex.schema.createTable('users', function(table) {
table.increments()
table.string('email').notNullable();
table.string('password').notNullable();
})
};

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

位置表

exports.up = function(knex, Promise) {
return knex.schema.createTable('locations', function(table) {
table.increments('id');
table.string('placename').notNullable();
table.float('latitude').notNullable();
table.float('longitude').notNullable();
table.integer('user_id').notNullable().references('id').inTable('users').onDelete('cascade');
})
};

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

用户种子

exports.seed = function(knex, Promise) {
// Deletes ALL existing entries
return knex('users').del()
.then(function () {
// Inserts seed entries
return knex('users').insert([
{email: 'allie@gmail.com', password: 'p1'},
{email: 'bob@gmail.com', password: 'p2'},
{email: 'minnie@gmail.com', password: 'p3'}
]);
});
};

位置种子

exports.seed = function(knex, Promise) {
// Deletes ALL existing entries
return knex('locations').del()
.then(function () {
// Inserts seed entries
return knex('locations').insert([
{placename: 'Himeji', latitude: 34.8394, longitude: 134.6939, user_id: 1},
{placename: 'Long Beach', latitude: 33.7701, longitude: 118.1937, user_id: 3},
{placename: 'Seattle', latitude: 47.6253, longitude: 122.3222, user_id: 2}
]);
});
};

最佳答案

作为答案,因为对于评论来说太大了。

嗯,错误消息很清楚,表明您违反了外键 约束。

这是因为要在 locations 中插入一行,您还需要提供一个 user_id,它引用表中的列 id 用户。如果该特定用户不在 users 表中,则不能将该 user_id 插入位置。看到这一行

table.integer('user_id').notNullable().references('id').inTable('users').onDelete('cascade');

所以首先你必须在 users 表中添加那个 user,然后你可以将它插入 location

关于javascript - Postgres/Knex "insert or update on table "位置“违反外键约束”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44212545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com