【问题标题】:Postgres/Knex "insert or update on table "locations" violates foreign key constraint"Postgres/Knex“在表“位置”上插入或更新违反了外键约束”
【发布时间】:2017-05-27 03:08:32
【问题描述】:

当我尝试在 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}
      ]);
    });
};

【问题讨论】:

    标签: javascript postgresql knex.js


    【解决方案1】:

    作为答案,因为它太大而无法发表评论。

    嗯,错误消息很清楚,您违反了foreign key 约束。

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

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

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

    【讨论】:

    • 谢谢,是的,我意识到我的种子坏了。因此,我什至在创建用户之前尝试使用引用用户的外键创建位置。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 2020-12-02
    • 2020-06-28
    • 1970-01-01
    • 2015-08-19
    • 2020-09-07
    • 2020-02-07
    相关资源
    最近更新 更多