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?

【Laravel】リレーションの書き方

Last updated at Posted at 2024-10-02

はじめに

以下はLaravelでAPIを使用してリレーション先を操作するための手順をまとめたメモになります

データの取得方法

データを取得する基本的な方法は、

  • 1対1 (One to One)
  • 1対多 (One to Many)
  • 多対多 (Many to Many)
    それぞれ同様の方式で行えます。

1対1 (One to One) のリレーション

「1対1」のリレーションでは、1つのレコードが他の1つのレコードと対応します。

Modelによるリレーションの設定

User.php
class User extends Model
{
    public function profile()
    {
        return $this->hasOne(Profile::class);
    }
}
Profile.php
class Profile extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
  • hasOne()はUserモデルが1つのProfileを持っていることを示します
  • belongsTo()はProfileが1人のUserに属していることを示します

多対1 (Many to One) のリレーション

「多対1」のリレーションでは、複数のレコードが1つのレコードに関連付けられます。

Modelによるリレーションの設定

  • hasMany()はUserモデルが複数のPostを持つことを示します
  • belongsTo()はPostが1人のUserに属していることを示します。
User.php
class User extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}
Post.php
class Post extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

多対多 (Many to Many) のリレーション

「多対多」のリレーションでは複数のレコードが複数のレコードに関連付けられます。

中間テーブルの作成

多対多リレーションでは、テーブルとテーブルを関連付けるために中間テーブルを作成します。中間テーブルには各々のテーブルと関連付けする外部キーを用意することで、それぞれのテーブルを関連付けすることができます

データの取得例

users テーブルからIDが1のレコードを取得し、それからそのユーザーに紐付いた profiles テーブルのレコードを取得します。

$profile には profiles テーブルのデータのみが格納されます。

***controller.php
$user = User::find(1);
$profile = $user->profile;

users テーブルのデータも同時に使用したい場合は、$user 変数をそのまま使うか、withメソッドを使ってリレーション先のデータを最初のクエリと一緒に取得することができます

***controller.php
$user = User::with('profile')->find(1);

まとめ

  • 1対1: hasOne()belongsTo() を使う
  • 多対1: hasMany()belongsTo() を使う
  • 多対多: belongsToMany() を使う(中間テーブルが必要)
  • 「データを取得する基本的な方法は全て同じ」
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?