1
我有兩個表accounts
和projects
:Postgres的更新插入之前,新的變量在觸發器
create table accounts (
id bigserial primary key,
slug text unique
);
create table projects (
id bigserial primary key,
account_id bigint not null references accounts (id),
name text
);
我希望能夠插入新行projects
通過指定唯一account.slug
(不account.id
)。我想要實現的是一樣的東西:
INSERT into projects (account_slug, name) values ('account_slug', 'project_name');
我想過使用觸發器(遺憾的是它不工作):
create or replace function trigger_projects_insert() returns trigger as $$
begin
if TG_OP = 'INSERT' AND NEW.account_slug then
select id as account_id
from accounts as account
where account.slug = NEW.account_slug;
NEW.account_id = account_id;
-- we should also remove NEW.account_slug but don't know how
end if;
return NEW;
end;
$$ LANGUAGE plpgsql;
create trigger trigger_projects_insert before insert on projects
for each row execute procedure trigger_projects_insert();
什麼是要做到我的最好辦法米試圖做什麼?
觸發是一個好主意嗎? 有沒有其他解決方案?
感謝您的回覆,我使用https://postgrest.com/en/v0.4/,不知道您是否熟悉它,即使您的解決方案正確,也不會真正起作用使用postgrest,這就是爲什麼我想使用觸發器。 – julesbou
我想說,如果不能正確使用數據庫,應該使用不同的東西,但它可能不適用於您的選擇。我會添加一個不同的想法,也許這將有所幫助。 –