我有两个相互引用的表.举个例子,假设它们是帖子和 comments :

Posts
-----
id           bigint
title        text
body         text

Comments
--------
id           bigint
post_id      bigint references Posts
body         text

在我的应用程序中,没有至少一条 comments 的帖子是没有意义的.因此,如果用户创建了某个内容,则必须从一个帖子和与该帖子相关的 comments 开始(稍后,他们可以向该帖子添加其他 comments ).

在Supabase中,有没有办法同时创建一个新的帖子和一个引用这个新帖子的新 comments ?

supabase
  .from("posts")
  .insert({title: 'new post', body: 'body of new post'})
  .select({ id })
  .then()
  .from("comments")
  .insert({post_id: id, body: 'comment body'})

在Rails中,我相信有一些类似于

transaction do 
  # ...
end

这几乎就是我在suabase js客户端中要寻找的东西.如果不存在,有没有办法在PostgreSQL中这样做(然后用Supabase.rpc()运行它)?

推荐答案

有两种方法可以实现这一点:

  1. 将逻辑封装在postgres函数中,然后将其称为RPC.类似于:
CREATE OR REPLACE FUNCTION create_post_and_comment(
    post_title TEXT,
    post_body TEXT,
    comment_body TEXT
) RETURNS VOID AS $$
BEGIN
    -- Insert a new post into the "posts" table
    INSERT INTO posts (title, body)
    VALUES (post_title, post_body)
    RETURNING id INTO id;

    -- Insert a new comment into the "comments" table
    INSERT INTO comments (post_id, body)
    VALUES (id, comment_body);
END;
$$ LANGUAGE plpgsql;
  1. 在POST表上创建触发器以创建 comments 条目:
-- Create a function that inserts a comment
CREATE OR REPLACE FUNCTION insert_comment()
RETURNS TRIGGER AS $$
BEGIN
    INSERT INTO comments (post_id, body)
    VALUES (NEW.id, 'Default comment text'); -- You can change the default comment text as needed
    RETURN NULL; -- Returning NULL because we are only inserting into "comments" and not modifying the "posts" table
END;
$$ LANGUAGE plpgsql;

-- Create a trigger that fires after inserting into "posts"
CREATE TRIGGER after_insert_post
AFTER INSERT ON posts
FOR EACH ROW
EXECUTE FUNCTION insert_comment();

请注意,如果您将每个帖子中的所有 comments 存储在JSON/JSONB字段中,则触发器将是一种更好的方法.

Postgresql相关问答推荐

如何接受jsonb路径中的任何密钥?

使用来自 docker 图像的 postgres 设置 Keycloak 21

是否可以在 postgres jsonb 列中的列表上创建索引

如何在 MockDataProvider 中创建自定义 JOOQ 记录?

Postgres 14 反斜杠 Z 没有给出正确的输出

为什么 postgresql 可以在这个查询中高效地使用索引?

使用 postgresql Select 整数作为位和状态表

我应该使用哪个 postgresql 包?

OpenShift:如何从我的 PC 连接到 postgresql

在 PostgreSQL 中Explain与explain analyze

如果 PostgreSQL 数据库中存在,则删除表

psql:致命:connection requires a valid client certificate

从 Select 中创建一个临时表,如果表已经存在则插入

为 Django Postgres 连接强制 SSL

将属性添加到 Sequelize FindOne 返回的对象

postgresql 查询以显示用户的组

有没有办法确保 WHERE 子句在 DISTINCT 之后发生?

与 iexact 一起使用时,Django get_or_create 无法设置字段

PostgreSQL - 如何在不同时区呈现日期?

postgresql NOT ILIKE 子句不包含空字符串值