1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

紐づいたテーブルにデータが反映されない症状の解決方法について

Posted at

はじめに

開発中usersテーブルにフォームに入力したデータをonSubmitで登録しても紐づいたuser_skillテーブルにデータが追加されない箇所でつまずいたため、解決方法を共有させていただきます。なお、Foreign key設定はsupabaseで設定済です。


このように記述していました。

users.ts
import { supabase } from "../../utils/supabase";
import { UserParams } from "../../domain/users";

export async function insertUsers(user: UserParams): Promise<UserParams>{
  const { data, error } = await supabase.from("users").insert([{
   user_id: user.user_id, name: user.name, description: user.description, github_id: user.github_id, qiita_id: user.qiita_id, x_id: user.x_id}])
  .select();

  if (error) {
    console.error(error);
    throw error;
  }
  if (!data || data.length === 0) {
    throw new Error("データがありません");
  }

  user.skill_id?.map(skillId => ({
    user_id: user.user_id,
    skill_id: skillId
  }))

  const { error: skillError} = await supabase.from("user_skill").insert([{user_id: user.user_id, skill_id: user.skill_id}])
  if (skillError) {
    console.error(skillError);
    throw skillError;
  }


  return data[0] as UserParams;
}

解決方法

user_skillテーブルにuser.skill_idを配列で追加する
Promiseの型もuserとskillsの2つ指定し、最後に返すことでコンソールでも出力できました。

users.ts
import { supabase } from "../../utils/supabase";
import { UserParams } from "../../domain/users";

export async function insertUsers(user: UserParams): Promise<{user: UserParams; skills: {skill_id: number }[]}>

{
  const { data, error } = await supabase.from("users").insert([{
   user_id: user.user_id, name: user.name, description: user.description, github_id: user.github_id, qiita_id: user.qiita_id, x_id: user.x_id}])
  .select();

  if (error) {
    console.error(error);
    throw error;
  }
  if (!data || data.length === 0) {
    throw new Error("データがありません");
  }

  
  const { error: skillError} = await supabase.from("user_skill")
  .insert(user.skill_id?.map(skillId => ({
    user_id: user.user_id,
    skill_id: skillId
  })));

  if (skillError) {
    console.error(skillError);
    throw skillError;
  }

  return {
    user: data[0] as UserParams,
    skills: user.skill_id?.map(skillId => ({ skill_id: skillId})) || []
  };
}
Register.tsx
// supabaseにデータ登録
  const onSubmit = async (data: UserParams) => {
    try {
      const insertedUser = await insertUsers(data);
      console.log("insertedUserの中身", insertedUser)
    } catch (error) {
      console.error(error);
    }
  };

おわりに

これで、意図した動きになってくれました。


1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?