[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');
}
}#テーブルイメージ
#中間テーブルのタイムスタンプを利用する
リレーションに ->withTimestamps() を追加する
これにより中間テーブルのタイムスタンプを更新することが出来る。
class User extends Model
{
public function roles(): BelongsToMany
{
return $this->belongsToMany(Role::class, 'user_role', 'user_id', 'role_id')
->withTimestamps();
}
}