如何在Supabase中拉取表中的数据并将其输出为JSON

yr9zkbsy  于 2023-08-08  发布在  其他
关注(0)|答案(1)|浏览(138)

我是一个新的supbase和使用SQL编辑器创建函数,我可以在我的Flutterflow应用程序中使用。我遇到的问题是抓取数据并将其输出为JSON。我可以这样做,但在表的形式,但我需要它在JSON中再次更改它。下面是我目前使用的代码,它输出为JSON,但只有一行(可能是因为我使用了record作为数据类型)

CREATE OR REPLACE FUNCTION get_dashboard_company_registration(start_date date, end_date date)
RETURNS JSON AS $$
DECLARE
  t_id integer;
  t_plan_name text;
  t_created_at timestamp;
  t_count integer;
  datas record;
  jsondata jsonb;
  current_date date := start_date;
  date_array date[];
BEGIN
  SELECT
    p.id, p.plan_name, pr.created_at, count(p.id) as count
  INTO datas
  FROM profiles as pr
  JOIN user_subscription_plans as usp
    ON usp.user_id = pr.id
  JOIN plans as p
    ON usp.plans_id = p.id
  GROUP BY p.id, p.plan_name, pr.created_at
  ORDER BY pr.created_at;

  return json_build_object('data', datas);
END;
$$ LANGUAGE plpgsql security definer;

字符串

brgchamk

brgchamk1#

您只需要将SQL查询 Package 在SQL函数中。我想你在问题中遗漏了where子句。

CREATE OR REPLACE FUNCTION get_dashboard_company_registration(start_date date, end_date date)
RETURNS JSON LANGUAGE SQL security definer AS
$$
select json_agg(to_json(t.*)) from
( 
  -- your query w/o INTO and a WHERE clause added
  SELECT p.id, p.plan_name, pr.created_at, count(p.id) as count
  FROM profiles as pr
  JOIN user_subscription_plans as usp ON usp.user_id = pr.id
  JOIN plans as p ON usp.plans_id = p.id

  -- added by me
  WHERE pr.created_at::date between start_date and end_date  

  GROUP BY p.id, p.plan_name, pr.created_at
  ORDER BY pr.created_at
) as t
$$;

字符串
但我不确定你是否需要一个函数。为什么不使用带参数的查询(例如:start_date:end_date

相关问题