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

NextJs+Supabase提交文章时无法插入Auth用户ID至posts表求助

解决方案

要实现将认证用户的user.id插入到posts表的id列,你需要先获取当前登录的用户信息,再将用户ID与文章内容一起提交。以下是修改后的完整代码:

"use client";
import { useState } from "react";
import supabase from "@/utils/supabase/client";

export function Edit() {
  const [body, setBody] = useState("");

  const handleSubmit = async (e: { preventDefault: () => void }) => {
    e.preventDefault();

    // 获取当前认证用户
    const { data: authData, error: authError } = await supabase.auth.getUser();
    if (authError || !authData.user) {
      console.error("用户未登录或获取用户信息失败:", authError?.message);
      return;
    }

    const userId = authData.user.id;

    // 插入文章时携带用户ID到posts表的id列
    const { data, error } = await supabase.from("posts").insert([
      { id: userId, body }
    ]);
    
    if (data) {
      setBody("");
      window.location.reload();
    }
    if (error) {
      console.error("插入文章失败:", error);
    }
  };

  return (
    <div>
      <form onSubmit={handleSubmit} className="flex flex-col text-black">
        <label htmlFor="postsBody" className="text-white">
          Note Title:
        </label>
        <input
          id="postsBody"
          className="mt-5"
          type="text"
          value={body}
          onChange={(e) => setBody(e.target.value)}
          required
        />
        <button
          type="submit"
          className="bg-white p-3 rounded mt-5 text-black font-bold"
        >
          Add Contents
        </button>
      </form>
    </div>
  );
}

关键修改点说明

  • 获取当前认证用户:通过supabase.auth.getUser()获取当前登录的用户对象,确保用户已完成认证后再执行插入操作,如果用户未登录或获取失败,直接终止流程并打印错误信息。
  • 携带用户ID插入数据:在insert方法的参数中添加id: userId,将认证用户的user.id赋值给posts表的id列,与文章内容body一起提交。

额外注意事项

如果你的posts表中id列是默认的自增UUID主键,直接插入用户ID可能会违反主键唯一性限制(当多个用户尝试发布文章时,用户ID重复会导致插入失败)。这种情况下更合理的设计是在posts表中新增一个user_id列(用于存储发布者ID),而保留id作为文章自身的唯一标识。如果是这种场景,只需将插入代码改为:

await supabase.from("posts").insert([
  { user_id: userId, body }
]);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 00:33:24