Adding a column as a foreign key gives ERROR column referenced in foreign key constraint does not exist

前端 未结 5 573
抹茶落季
抹茶落季 2021-01-31 13:02

I have the following set up,

CREATE TABLE auth_user ( id int PRIMARY KEY );
CREATE TABLE links_chatpicmessage ();

I\'m trying to add a

5条回答
  •  感情败类
    2021-01-31 14:00

    The CONSTRAINT clause is optional. I suggest ommiting it and always letting PostgreSQL autoname the constraint, without naming it you'll get a logical name

    "links_chatpicmessage_sender_fkey" FOREIGN KEY (sender) REFERENCES auth_user(id)
    

    That's what you'll likely want to know if an INSERT or UPDATE fails due to a constraint violation.

    Syntax to add a foreign key

    All of these are somewhat documented on ALTER TABLE

    To a new column

    ALTER TABLE links_chatpicmessage 
      ADD COLUMN sender int,
      ADD [CONSTRAINT foo] FOREIGN KEY (sender) REFERENCES auth_user(id);
    

    This is compound and transactional. You can issue two ALTER statements on the same table by separating the two statements with a ,.

    To a preexisting column

    -- assumes someone has already added the column or that it already exists
    ALTER TABLE links_chatpicmessage
      ADD COLUMN sender int;
    
    ALTER TABLE links_chatpicmessage
      ADD [CONSTRAINT foo] FOREIGN KEY (sender) REFERENCES auth_user(id);
    

提交回复
热议问题