Insert or update on table violates foreign key constraint PSQL/Knex

4.4k views Asked by At

This is my first psql database. I'm using knex.

I have 3 tables: users, users_posts, and users_comments. I want to set it up so that users can post things and also comment on other users posts.

When I seed the users_comments I get this error:

insert or update on table "users_comments" violates foreign key constraint

How can I modify my tables to get the users_comment table to accept the foreign post_id key? Or is there a better way for me to set up comments with post and users?

users table

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

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_comments table

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_comments seed:

    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')
1

There are 1 answers

0
TYPOI On BEST ANSWER

Got it working. Made these changes to user_comments ...

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);