mochotomochotoロゴ

[Laravel Eloquent]多対多のリレーション

広告Laravel
2023年09月28日

Laravel リレーションの多対多の場合の利用方法です。

#中間テーブル名を指定する

public function roles(): BelongsToMany
{
    return $this->belongsToMany(Role::class, 'role_user');
}

#中間テーブルのキー名を指定する

belongsToMany('関係先モデル', '中間テーブル名', '関係元と紐づく中間テーブルカラム名', '関係先と紐づく中間テーブルカラム名');
class User extends Model
{
    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(Role::class, 'user_role', 'user_id', 'role_id');
    }
}

#テーブルイメージ

erDiagram users ||--o{ user_role:"" roles ||--o{ user_role:"" users { bigint id PK } user_role { bigint user_id PK bigint role_id PK } roles { bigint id PK }

#中間テーブルのタイムスタンプを利用する

リレーションに ->withTimestamps() を追加する これにより中間テーブルのタイムスタンプを更新することが出来る。

class User extends Model
{
    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(Role::class, 'user_role', 'user_id', 'role_id')
            ->withTimestamps();
    }
}

#参考

10.x Eloquent:リレーション Laravel

readouble.comreadouble.com