0
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初心者メモ】リレーションの取得

Posted at

Supabaseにおいて、リレーション(関連テーブル)データの取得方法は大きく分けて2通りあります。

方法1:暗黙的リレーション

外部キーのリレーションを自動で推測し、その名前を省略して関連テーブルのデータを取得できる方法です。つまり、外部キー制約が設定されていれば、テーブル名(取得カラム...) の形だけで簡単にリレーション先のデータを取得できます。

基本:

const { data, error } = await supabase
  .from('親テーブル名')
  .select(`
    親のカラム1,
    親のカラム2,
    関連テーブル名 (
      関連テーブルのカラム1,
      関連テーブルのカラム2
    )
  `);

例:

const { data, error } = await supabase
  .from('posts')
  .select(`
    id,
    title,
    content,
    users ( id, name )
  `)

方法2:明示的リレーション

リレーション(外部キー)を使って関連テーブルのデータを取得する際に、どのテーブルのどの外部キーを使うかを明確に指定する方法です。特に、外部キーが複数ある場合、取得するリレーションに別名をつけたい場合に役立ちます。

基本:

<エイリアス>:<参照先テーブル>!<外部キー名> ( <取得カラム1>, <取得カラム2>, ... )

例:

const { data, error } = await supabase
  .from('posts')
  .select(`
    id,
    title,
    content,
    author:users!posts_author_id_fkey ( id, name )
  `)
0
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
0
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?