5
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.

Laravel8 リレーション

Posted at

Laravel初学者です。
オリジナルアプリを作成しているのでその過程を記事にしています。

理解が曖昧なところも多いため、ご指摘等ありましたらご連絡いただければ幸いです。

今回はリレーションについて勉強したのでそのまとめです。
自分用メモです。

環境

Version
PHP 7.4.14
Laravel 8.24.0
mysql 8.0.23
docker 20.10.2
docker-compose 1.27.4

参考

こちらから勉強させていただきました。

翻訳してくれてありがたい。。。

今回の設定

  • Phoneモデル
  • Userモデル

こちらの2つが存在しいろいろな場合で定義します

1対1

App/Models/User.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function phone()
    {
        return $this->hasOne(Phone::class);
    }
}
App/Models/Phone.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Phone extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

上記のようにそれぞれモデルに定義します。
1対1の関係ってどちらがhasOneで、どちらがbelongsToか分かりにくいので
私は
親=それが存在しないとそもそも子も存在しないモデルが親
子=自分が消えても親は消えないモデルが子
というように覚えてます。

つまり今回の場合でいうとUserモデルが親でPhoneモデルが子です。

例えば
投稿に対してコメントできる機能があった時には

  • 投稿が消えたらその投稿に対するコメントも消えるべき
  • コメントはそもそも投稿が存在しないとそのコメントは存在しない

ということを踏まえると投稿が親でコメントが子です。

分かりにくい。。。
DB設計って難しい。

1対多

UserはたくさんのPhoneを持っている関係です。
User:1
Phone:多

App/Models/User.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function phones()
    {
        return $this->hasMany(Phone::class);
    }
}

ここで注意なのはphonesと複数形になっていることです。
たくさんのphoneなので複数と覚えました。

App/Models/Phone.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

今回はuserは1なので単数形です。
1つのphoneを持つのはは1人のuserしか存在しないということです。

5
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
5
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?