Search code examples
postgresqlforeign-keysmany-to-many

Are 'link tables' in postgresql supposed to automatically update when records are added to primary tables?


Noob question - Basically I'm trying to get a link table for a many-to-many relationship to auto update. I don't really know if this is what is supposed to happen, but I don't think I'm supposed to manually copy data into it either.

Below is my DDL - if glo.link_table is made this way, and I add data to both glo.collectors and glo.natural_hazards, shouldn't glo.link_table auto-update? Right now glo.link_table is not doing anything when I copy data into to glo.collectors and glo.natural_hazards. I'm guess I'm expecting glo.link_table to like add records when I add data to those two tables.

    --Drop if exsits & create
DROP TABLE IF EXISTS  glo.collectors CASCADE;
 
-- Make collectors table
CREATE TABLE glo.collectors (
  u_id serial,
  user_name text NOT NULL,
  password text NOT NULL,
  email text NOT NULL,
  agency text NOT NULL,
  PRIMARY KEY (u_id)
);
 
--Drop if exsits & create
DROP TABLE IF EXISTS glo.natural_hazards;
 
-- Create natural hazards table
CREATE TABLE IF NOT EXISTS glo.natural_hazards(
      nathaz_id SERIAL,
      data_version text, 
      data_class text, -- class = foundational  
      agency text NOT NULL,
      data_owner text,
      data_url text NOT NULL,
      keywords text,
      spatial_ref text,
      creation_date text,
      data_description text,
      data_purpose text, 
      fema_sfha text,
      event_inundation text,
      video_catalog text,
      hazard_scale text,
      PRIMARY KEY (nathaz_id)
);
 
--Drop if exsits & create
DROP TABLE IF EXISTS glo.link_table;
 
-- Create link table
CREATE TABLE IF NOT EXISTS glo.link_table(
      u_id int REFERENCES glo.collectors (u_id) ON UPDATE CASCADE ON DELETE CASCADE,
      nathaz_id int REFERENCES glo.natural_hazards (nathaz_id) ON UPDATE CASCADE,
      CONSTRAINT link_table_pkey PRIMARY KEY (u_id, nathaz_id) 
      );

Solution

  • No the link_table will not auto populate. Those columns will act in a similar way to a 'foreign key' and ensure that there is some form of constraint on what can be inserted into these columns.

    Data that already exists in the link_table will be affected by changes to data in the tables that these columns reference. But this data will have to be inserted separately.

    column references documentation

    For automatically inserting data into the link_table I would suggest possibly using a trigger.

    Trigger documentation