【问题标题】:Insert or update on table violates foreign key constraint PSQL/Knex在表上插入或更新违反外键约束 PSQL/Knex
【发布时间】:2016-12-18 05:17:23
【问题描述】:

这是我的第一个 psql 数据库。我正在使用 knex。

我有 3 个表:users、users_posts 和 users_cmets。我想设置它,以便用户可以发布内容并评论其他用户的帖子。

当我播种 users_cmets 时,我收到此错误:

在表“users_cmets”上插入或更新违反了外键约束

如何修改我的表以使 users_comment 表接受外部 post_id 键?或者我有没有更好的方法来设置带有帖子和用户的 cmets?

用户表

table.increments();
table.string('username').notNullable().defaultTo('').unique();
table.string('email').notNullable().unique();
table.specificType('hashed_password', 'char(60)').notNullable();
table.timestamps(true, true);

users_posts 表

table.increments();
table.integer('user_id')
 .notNullable()
 .references('id')
 .inTable('users')
 .onDelete('CASCADE')
 .index();
table.string('post_title').notNullable().defaultTo('');
table.string('post_content').notNullable().defaultTo('');
table.timestamps(true, true);

users_cmets 表

table.increments();
table.integer('user_id')
 .notNullable()
 .references('id')
 .inTable('users')
 .onDelete('CASCADE')
 .index();
table.integer('post_id')
  .notNullable()
  .references('id')
  .inTable('users_posts')
  .onDelete('CASCADE')
  .index();
table.string('comment_content').notNullable().defaultTo('');
table.timestamps(true, true);

users_cmets 种子:

    id: 1,
    user_id: 1,
    post_id: 1,
    comment_content:"...",
    created_at: new Date('2016-06-29 14:26:16 UTC'),
    updated_at: new Date('2016-06-29 14:26:16 UTC')

【问题讨论】:

    标签: postgresql foreign-keys knex.js


    【解决方案1】:

    搞定了。对 user_cmets 进行了这些更改...

    table.integer('user_id') 
     .notNullable() 
     .references('id') 
     .inTable('users') 
     .onDelete('CASCADE') 
     .index(); 
    table.integer('id') 
     .notNullable() 
     .references('user_posts') 
     .onDelete('CASCADE') 
     .index();    
    table.string('comment_content').notNullable().defaultTo('');
    table.timestamps(true, true); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-27
      • 2020-12-02
      • 2015-08-19
      • 2020-09-07
      • 2020-02-07
      • 1970-01-01
      • 1970-01-01
      • 2013-09-06
      相关资源
      最近更新 更多