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?

More than 3 years have passed since last update.

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

Posted at

はじめに

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

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

最終的なゴール

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

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

目的

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

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

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

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

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

やり方の概要を先に伝えておくと

前回やった、1対多の関係をForeign Key で作成して関係の設定を unique 制限をかければ1対1のリレーションシップはできます。

前回👇
https://qiita.com/ryosuketter/items/59a05d4eb5c715287ded

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

usersテーブル以外に、profilesテーブルを作成します。

Add_Table_-_Data___Hasura.png

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

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

Browse_-profiles-_Data___Hasura.png

では、次は、profilesテーブルとusersテーブルを1対1で連携させていきます。

テーブル同士の関連づけ

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

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

Modify_-users-_Data___Hasura.png

Foreign Keyの設定

Add Foreign Keysしてください。

Modify_-users-_Data___Hasura.png

Relationshipsタブにいきます

users

Relationships_-users-_Data___Hasura.png

Nameはprofileのまま、Saveします。

profiles

Relationships_-profiles-_Data___Hasura.png

Nameはuserのまま、Saveします。

これで、profilesテーブルとusersテーブルを1対1で連携できました。

データを追加していきましょう。

データの追加

usersテーブルから見ると

Browse_-users-_Data___Hasura.png

  • users.name = john の profile_idprofiles.nickname = Jon の profiles.id
  • users.name = bob の profile_idprofiles.nickname = bobby の profiles.id

割り当てていきましょう

Browse_-users-_Data___Hasura.png

関連づけました。

クエリで確認しましょう

usersから見る

API_Explorer___Hasura.png

profilesから見る

API_Explorer___Hasura.png

本日は以上です。

次回以降で、また別のHasuraのリレーションシップ(多対多を)見ていきます!

参考

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

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?