简体   繁体   中英

postgresql foreign key integer[] refers to integer

i'm working on a postgresql database and i have an issue :

i want to create a table applicant with a column categories_ids (that mean that an applicant can have multiple categories) and i want create a foreign key constraint between this column and the column id of categories table. But pgadmin says that is impossible :

foreign key constraint "fk_categories_ids" cannot be implemented
DÉTAIL : Key columns "categories_ids" and "id" are of incompatible types: integer[] and integer.

EDIT 1 :

CREATE TABLE public.applicants
(
-- Hérité(e) from table users:  id integer NOT NULL DEFAULT nextval('users_id_seq'::regclass),
-- Hérité(e) from table users:  email character(60) NOT NULL,
-- Hérité(e) from table users:  "firstName" character(50) NOT NULL,
-- Hérité(e) from table users:  "lastName" character(50) NOT NULL,
-- Hérité(e) from table users:  password character(50) NOT NULL,
-- Hérité(e) from table users:  role_id integer NOT NULL DEFAULT nextval('users_role_id_seq'::regclass),
  home boolean NOT NULL,
  "fullTime" boolean,
  "partTime" boolean NOT NULL,
  freelance boolean NOT NULL,
  internship boolean NOT NULL,
  "minSalary" integer,
  domain_id integer,
  categories_ids integer[],
  skills_ids integer[],
  locations_ids integer[],
  "jobExperiences_ids" integer[],
  CONSTRAINT pk_applicant_id PRIMARY KEY (id),
  CONSTRAINT fk_domain_id FOREIGN KEY (domain_id)
      REFERENCES public.domains (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)
INHERITS (public.users)
WITH (
  OIDS=FALSE
);

Delete the categories_ids integer[] field and:

create table applicant_category (
    applicant_id int references applicants(id),
    category_id int references category(category_id),
    primary key (applicant_id, category_id)
)

You cannot create FK on array column. Not supported. So either use EAV model ( https://en.wikipedia.org/wiki/Entity%E2%80%93attribute%E2%80%93value_model , so 3 tables instead of 2), or work without Foreign Keys (you can create custom triggers to emulate them, though).

There are some articles comparing EAV with using "non-primitive" ( int[] , hstore , jsonb ) data types -- for example http://coussej.github.io/2016/01/14/Replacing-EAV-with-JSONB-in-PostgreSQL/ and https://wiki.hsr.ch/Datenbanken/files/Benchmark_of_KVP_vs. hstore -_doc.pdf have some benchmarks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM