2017-03-09 137 views
1

我有兩個表accountsprojectsPostgres的更新插入之前,新的變量在觸發器

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(); 

什麼是要做到我的最好辦法米試圖做什麼?

觸發是一個好主意嗎? 有沒有其他解決方案?

回答

1
WITH newacc AS (
    INSERT INTO accounts (slug) 
     VALUES ('account_slug') 
     RETURNING id 
) 
INSERT INTO projects (account_id, name) 
    SELECT id, 'project_name' 
     FROM newacct; 

如果你在你可以使用SQL的限制,另一個想法可能會定義兩個表在上查看和創建底層表上執行兩個INSERT S中的視圖的INSTEAD OF INSERT觸發。然後一個INSERT聲明就像你問題中的聲明一樣。

+0

感謝您的回覆,我使用https://postgrest.com/en/v0.4/,不知道您是否熟悉它,即使您的解決方案正確,也不會真正起作用使用postgrest,這就是爲什麼我想使用觸發器。 – julesbou

+0

我想說,如果不能正確使用數據庫,應該使用不同的東西,但它可能不適用於您的選擇。我會添加一個不同的想法,也許這將有所幫助。 –