Can i have one foreign key to both parent and it's childs in postgresql? I want to have a foreign key to reference table and it's children. Here's how I tried and failed:

CREATE TABLE parent (
 id serial,
 CONSTRAINT parent_pk PRIMARY KEY(id)
);

CREATE TABLE child (
  val text,
  constraint child_pk PRIMARY KEY(id)
) INHERITS(parent);

CREATE TABLE test (
  id serial,
  foreign_id bigint REFERENCES parent(id),
  constraint testpk PRIMARY KEY (id)
)


Lets say we have such data:

parent:
|id| 
+--+
|1 | --public.parent oid
|2 | --public.child oid

child:
|id|val|
+--+---+
|2 |'a'| --public.child oid


what i whant to acheive is this:

test:
|id|foreign_id|
+--+----------+
|1 | 1        | --(from public.parent table)
|2 | 2        | --(from public.child table)


is there a good workaround here?
this is not possible out of the box. inheritance in PostgreSQL is based on individual tables, which are only logically connected through pg_inherit. Each table is still somewhat independent. Therefore you cannot create a key on the entire structure. It is only possible to reference individual tables. What you can do, however, is to write a trigger ensuring integrity. A foreign key is basically the same behind the scenes anyway.