Skip to content

建立 2026-09-14 更新 2026-09-14

資料表與自動 API

在 Dashboard 的 Table Editor 新增資料表,等同在 Postgres 執行 CREATE TABLE。存檔後,PostgREST 立刻為這張表提供 REST 端點,Client 用 .from('table_name') 就能讀寫。

用 Table Editor 建表

以待辦事項為例,建議至少這些欄位:

欄位 型別 說明
id uuidbigint 主鍵;uuid 可用 gen_random_uuid() 當預設值
user_id uuid 對應 auth.users.id,給 RLS 判斷「這列是誰的」
task text 工作內容
is_complete boolean 預設 false
created_at timestamptz 預設 now()

建表時 Dashboard 會問要不要啟用 RLS。選啟用。 沒開 RLS 的表,任何持有 publishable key 的人都能讀寫全部列。

外鍵請連到 auth.users(或你自己的 profiles 表),不要只在前端「假裝」這筆資料屬於目前使用者。沒有 user_id,RLS 就沒有可判斷的欄位。

自動產生的 API

建表 todos 之後,不必寫後端路由。底層大致是:

GET /rest/v1/todos
POST /rest/v1/todos
PATCH /rest/v1/todos?id=eq.1
DELETE /rest/v1/todos?id=eq.1

請求必須帶 apikey(publishable 或 secret key)。已登入時還要帶使用者的 JWT。實務上用 JavaScript Client,不要手組這些 URL。

GraphQL 端點也有,但入門先把 REST + Client 做熟即可。

關聯怎麼查

Postgres 的強項是關聯。例如 todosuser_id 指向 profiles

const { data, error } = await supabase
  .from('todos')
  .select('id, task, profiles(display_name)')

select 字串裡的 profiles(...) 是 PostgREST 的嵌入語法,前提是資料庫裡真的有外鍵。沒有外鍵就嵌不進去,這是特性不是 bug。

下一步