Postgresql postgres在插入触发器之前更新新变量

Postgresql postgres在插入触发器之前更新新变量,postgresql,triggers,Postgresql,Triggers,我有两个表账户和项目: 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 ); 我希望通过仅

我有两个表
账户
项目

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
);
我希望通过仅指定
account.slug
(而不是
account.id
),能够在
项目中插入新行。我想要达到的目标是:

INSERT into projects (account_slug, name) values ('account_slug', 'project_name');
我考虑过使用触发器(不幸的是它不起作用):

实现我想要做的事情的最佳方式是什么

扳机是个好主意吗? 还有其他解决办法吗

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
触发器,该触发器在基础表上执行两个
INSERT
s。然后像你问题中的那样插入一个
语句就行了。

谢谢你的回答,我正在使用,不知道你是否熟悉它,你的解决方案即使正确,也无法使用postgrest,这就是我想使用触发器的原因。我想说,如果它妨碍您正确使用数据库,您应该使用不同的触发器,但这可能不是您的选择。我会补充一个不同的想法,也许会有帮助。
WITH newacc AS (
   INSERT INTO accounts (slug)
      VALUES ('account_slug')
      RETURNING id
)
INSERT INTO projects (account_id, name)
   SELECT id, 'project_name'
      FROM newacct;