1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Hasuraのリレーションシップ(多対多)

Last updated at Posted at 2021-10-23

はじめに

以下のゴールを達成するため、本日は Hasuraの リレーションシップを学んでいきます。

今回はHasuraを使って1対1のリレーションを作る方法を見ていきます。

最終的なゴール

以下のような構成のアプリを作ることです。

スクリーンショット 2021-10-18 17.27.41.png

目的

  • 仕事で使っている技術のキャッチアップと復習
  • 使う可能性がある技術の理解度向上

Hasuraのリレーションシップ(1対1)

今回説明するHasuraのリレーションシップ(多対多)の概念図です。

スクリーンショット 2021-10-23 21.35.41.png

Hasuraを使って、どうやって多対多のリレーションを実現するかですが、中間テーブルを使って実現しています。

中間テーブルテーブルを使って、usersテーブルとprofilesテーブルそれぞれのidを関連づけてマッピングをしていきます。

これを実際に、テーブルや関連づけやデータを追加することで実現していきます。

中間テーブルの作成とデータの追加

Add_Table_-_Data___Hasura.png

👇それぞれAddします。

Relationships_-profile_users-_Data___Hasura.png

Nameもデフォのもので。

Relationships_-profile_users-_Data___Hasura.png

これで

  • profile_users.profile_idprofiles.idと多対1
  • profile_users.user_idusers.idと多対1

で、関連づけられました。

づぎに、profilesusersを見ていきましょう。

👇提案されていますね。1対多で。

Relationships_-profiles-_Data___Hasura.png

Nameもデフォのものでsaveします。。

これで、関連付け完了です。

続いて、データを追加します。

profile_usersテーブルをこんな感じの関連付けにしましょう。

id profile_id user_id
1 bob john
2 bob lilly
3 john bob
4 john lilly

いつものように、profile_usersテーブルに対して「Insert Rows」で2つ作成して、「Browse Rows」で確認します。

Browse_-profile_users-_Data___Hasura.png

テーブル同士の関連づけ

profilesテーブルとusersテーブルを1対多の関係で関連づけます。

usersテーブルに行って、Modifyを選んで、新しいカラムを作成します。

クエリで確認しましょう

profile_usersから見る

API_Explorer___Hasura.png

usersから見る

API_Explorer___Hasura.png

  • lillyはbobbyやJonから参照されています
  • johnはbobbyから参照されています
  • bobはJonから参照されています

ということがわかります。

どうやって探索しているかというと、lillyの場合

lillyのuser.id(5f172cd2-221c-4ea5-8b83-6420b18860ab)に、profile_usersテーブルをみて紐づいた profile_idを見ると、bobbyとJonが引っかかる。という感じですね。

本日は以上です。

これで、Hasuraの基本事項は学んだので、次で、Next.jsとapolloクライアントを使って、Hasuraとの連携を学びます。

参考

アウトプット100本ノック実施中

1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?