You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写PostgreSQL函数关联表并通过Supabase RPC返回扁平数据

实现扁平结构的关联查询PostgreSQL函数及Supabase调用

1. 创建PostgreSQL函数

根据你的表结构和关联需求,编写返回扁平结构的SQL函数:

CREATE OR REPLACE FUNCTION get_flattened_recipes()
RETURNS TABLE (
    product_name TEXT,
    recipe_id INT,
    instructions TEXT
) AS $$
BEGIN
    RETURN QUERY
        SELECT 
            r.product_name,
            r.recipe_id,
            i.instructions
        FROM recipes r
        JOIN instructions i ON r.instructions = i.recipe_id; -- 按你描述的关联条件,若实际是recipe_id关联则改为 r.recipe_id = i.recipe_id
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
  • SECURITY DEFINER 确保函数能访问到两个表的权限(若你的Supabase角色已有权限可省略)
  • 若你的关联逻辑实际是通过recipes.recipe_id关联instructions.recipe_id,替换JOIN条件即可

2. Supabase客户端调用

在前端使用supabase.rpc()调用该函数,直接获取扁平结构数据:

// JavaScript/TypeScript示例
const { data, error } = await supabase.rpc('get_flattened_recipes');

if (error) {
  console.error('查询出错:', error);
} else {
  console.log('扁平结构数据:', data);
}

返回的data数组中每个对象都会直接包含product_name、recipe_id、instructions字段,无嵌套结构。

内容的提问来源于stack exchange,提问作者Ripas55

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 00:18:24