Laravelで複数のモデル間の関係を定義するときは、BelongsToManyリレーションを使用すると便利です。例えば、UserとRoleモデル間の多対多関係を定義する場合、Userモデルにrolesメソッドを以下のように定義します。

```

public function roles()

{

return $this->belongsToMany('App\Role');

}

```

そして、Roleモデルにもusersメソッドを以下のように定義します。

```

public function users()

{

return $this->belongsToMany('App\User');

}

```

これにより、Userモデルのインスタンスから、そのユーザーが持つRoleモデルのコレクションを簡単に取得することができます。

#laravel

Reply to this note

Please Login to reply.

Discussion

No replies yet.