Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DB Error on delete:: Key (id)=(n) is still referenced from table "reviews" #4

Open
clock509 opened this issue Sep 26, 2020 · 2 comments

Comments

@clock509
Copy link

clock509 commented Sep 26, 2020

When I tried to delete a restaurant from 'Home.jsx', DB error occured with a message below:

ERROR: update or delete on table "restaurants" violates foreign key constraint "reviews_restaurant_id_fkey" on table "reviews"
DETAIL: Key (id)=(NUMBER) is still referenced from table "reviews".

So, when you create table 'reviews', you should add ON DELETE CASCADE at restaurant_id, otherwise the function DELETE doesn't work. So the implmented create table query is like as below:

CREATE TABLE reviews (
  id BIGSERIAL NOT NULL PRIMARY KEY,
  restaurant_id BIGINT REFERENCES restaurants(id) ON DELETE CASCADE NOT NULL,
  name VARCHAR(50) NOT NULL,
  review TEXT NOT NULL,
  rating INT NOT NULL check(rating >=1 AND rating <= 5)
);
@jbrian31
Copy link

jbrian31 commented Oct 4, 2020

If you have already created the table reviews with populated data and dont want to delete it, run the following SQL to alter it without dropping the table and re-adding it. Postgres requires you to drop a constraint on a foreign key, cant add the DELETE CASCADE, you must then readd the constraint.

ALTER TABLE reviews DROP CONSTRAINT reviews_restaurant_id_fkey, ADD CONSTRAINT reviews_restaurant_id_fkey FOREIGN KEY (restaurant_id) REFERENCES restaurants(id) ON DELETE CASCADE;

@yash-sharma01
Copy link

Thank you for this solution! @clock509 and @jbrian31

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants