4
2

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.

【Laravel】「 One To One (1対1)」リレーションを学ぶ

Last updated at Posted at 2022-02-10

「One To One 」リレーションを学ぶ

Laravel で使用できるデータベーステーブルのリレーションについて、今回は、「One To One」(1対1)の連携方法について記事を書きたいと思います。

基本的で理解しやすい「 One To One 」

基本的なリレーションとして「 One To One 」(1対1)の連携方法を勉強していきます。今回は例として、ユーザー情報を管理する User モデルと、ユーザー情報に関連付けられた個人情報を管理する Profile モデルを使って、双方の関係性について考えていきましょう。

User モデルと Profile モデルの関係

User モデルと Profile モデルの関係性を以下に表します。
Users テーブル と profiles テーブルがあり、双方の関係性は「 1対1 」となっています。profiles テーブルの user_idusers テーブルの外部キーとなっています。

Untitled Diagram(3).jpg

リレーションを定義して、モデル情報を取得する

両方のデータベースを横断して目的のデータを取得するために リレーション を定義してモデル情報を取得するための メソッド を書いていきます。

まずは、User モデルが Profile モデルの情報を取得するために、User モデルに profile メソッドを定義していきます。以下のような感じです。

user.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * User に関連する Profile 情報を取得するメソッド
     */
    public function profile()
    {
        return $this->hasOne(Profile::class);
    }
}

profile メソッドで、hasOne メソッドを呼び出しています。このメソッドの引数に、関連するモデルクラス(ここでは、Profile モデルクラス)を定義することで、目的のモデル情報を取得できるようになります。

例えば、User モデルでユーザーIDを絞って、そのユーザーIDに関連する Profile モデルを取得したい場合 は、

$profile = User::find(1)->profile;

という感じで、User モデルで ID を絞り込んでから、Profile モデルの情報を取得することができます。

一例として、usersテーブル の主キーのIDを絞ることができる find メソッドを使用後、profilesテーブル の各カラムの情報を得たい場合は、以下のようなコードになります。

// 指定した User モデルに関連する birthday 情報を得たい場合
$profile_birthday = User::find(1)->profile->birthday;

// 指定した User モデルに関連する phone 情報を得たい場合
$profile_phone = User::find(1)->profile->phone;

// 指定した User モデルに関連する address 情報を得たい場合
$profile_address = User::find(1)->profile->address;

先ほどの、リレーション定義によって、User モデルから Profile モデルへの橋渡しができていることが分かりますね。

逆に、「Profile」から「User」モデルの情報を取得したい場合

Profile モデルから User モデルへの関係性を定義する場合は 従属している意味をあらわす belongsTo メソッド を使用します。

profile.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Profile extends Model
{
    /**
     * この電話を所有しているユーザーの取得
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

user メソッドを新しく追加して、Userモデル との関係性を定義しています。ここで先ほどと同じく、2つのモデルのリレーションによって、Profiles テーブルから、Users テーブルの情報を得る例を見てみましょう。

// 指定した Profile モデルに関連する name 情報を得たい場合
$user_name = Profile::find(1)->user->name;

// 指定した Profile モデルに関連する email 情報を得たい場合
$user_email = Profile::find(1)->user->email;

Profile::find(1)profile テーブルの主キーである id を対象に絞り込みを行い、その後、絞り込んだレコード user_idUser モデルに対応する情報を取得します。

4
2
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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?