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?

supabaseでリレーションされたテーブルのデータを削除 エラー:update or delete on table "tableA" violates foreign key constraint "user_skill_user_id_fkey" on table "tableB"

Last updated at Posted at 2025-04-28

リレーションしてるテーブルを削除する際の必要操作

こんにちは!
前回、Supabaseでリレーションしたテーブルを作成する記事を書きました

今回はそのリレーションしたテーブルからデータを削除する際に発生したエラー と、その解決方法を記事にまとめます

発生したエラー

update or delete on table "users" violates foreign key constraint "user_skill_user_id_fkey" on table "user_skill"

リレーションの関係性

"user_skill" テーブルが "users" テーブルを参照

発生原因

"users" テーブルのデータを削除 しようとしたところ、エラーが発生

解決策

参照元(user_skill)を削除してから、元(users)を削除

実際に書いたコード

import 'dotenv/config';
import { supabase } from '../src/utils/supabase';

// user_skillを削除
const userSkillDelete = async (): Promise<void[]> => {
  const { data, error } = await supabase
    .from("user_skill")
    .delete()
    .neq("user_id", "")
    .select("*");
  if (error) {
    console.error("userSkillError:", error.message);
  }
  if (!data) {
    return [];
  }
  console.log("userSkillDelete", data);
  return data;
};

// usersを削除
const usersDelete = async (): Promise<void[]> => {
  const { data, error } = await supabase
    .from("users")
    .delete()
    .neq("user_id", "")
    .select("*");
  if (error) {
    console.error("UsersError:", error.message);
  }
  if (!data) {
    return [];
  }
  console.log("usersDelete", data);
  return data;
};

// 順番を守って削除
const deleteAll = async () => {
  await userSkillDelete();
  await usersDelete();
};

deleteAll();

ポイント

  • 先に参照元(user_skill)を削除 する
  • その後、元(users)を削除する
  • 削除の順番を守る ため、deleteAllでまとめ
  • 型はPromise<void[]>で良い

試したこと

  • 複数テーブルを同時指定するのは無理
    • .from("users, user_skill")とやったらエラー
    • relation "public.users, user_skill" does not exist

テーブルのデータを全て削除するコードについて

まとめ

リレーションされたテーブルからデータを削除する際は
削除の順番があるみたいです!

JISOUのメンバー募集中!

プログラミングコーチングJISOUでは、新たなメンバーを募集しています。
日本一のアウトプットコミュニティでキャリアアップしませんか?
興味のある方は、ぜひホームページをのぞいてみてくださ!
▼▼▼

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?