0

I have these tables on a database on Postgresql:

create table company (
  id bigint generated always as identity primary key,
  name text not null
);

create table employee (
  id bigint generated always as identity primary key,
  name text not null,
  company_id bigint not null references company(id)
);

create table manager_employee(
  id bigint generated always as identity primary key,
  manager_id bigint not null references employee(id),
  employee_id bigint not null references employee(id)
);
create unique index ux1_manager_employee on manager_employee(manager_id, employee_id);
alter table manager_employee add constraint ck1_manager_employee check (manager_id != employee_id);

I want to be sure that when I insert / update a value in manager_employee table both manager_id and employee_id belong to the same company, same company_id.

I think I have to use a trigger to ensure this condition, how can I create it?

Thanks

1 Answer 1

1

You can do it with constraints:

ALTER TABLE manager_employee ADD company_id bigint;

UPDATE manager_employee me
SET company_id = e.company_id
FROM employee e
WHERE me.employee_id = e.id;

ALTER TABLE manager_employee ALTER company_id SET NOT NULL;

ALTER TABLE employee ADD UNIQUE (company_id, id);

ALTER TABLE manager_employee ADD FOREIGN_KEY (company_id, manager_id)
   REFERENCES employee(company_id, id);

ALTER TABLE manager_employee ADD FOREIGN_KEY (company_id, employee_id)
   REFERENCES employee(company_id, id);

The unique constraint is as redundant as the new column, but is required as a target for the foreign key constraint.

Sign up to request clarification or add additional context in comments.

2 Comments

I don't understand the need of ALTER TABLE employee ADD UNIQUE (company_id, id); , id in employee is generated automatically. Can you explain please?
postgres will raise an error if there is no unique constraint on the referenced columns.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.