環境
Laravel v9.5.1 (PHP v8.1.3)
usersテーブル
id - integer
name - string
rolesテーブル
id - integer
name - string
role_userテーブル
user_id - integer
role_id - integer
Pivotを使わない場合
Models/RoleUser.php
class RoleUser extends Model
{
...
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function role(): BelongsTo
{
return $this->belongsTo(Role::class);
}
}
Models/User.php
class User extends Model
{
...
public function roleUsers(): HasMany
{
return $this->hasMany(RoleUser::class);
}
}
Models/Role.php
class Role extends Model
{
...
public function roleUsers(): HasMany
{
return $this->hasMany(RoleUser::class);
}
}
userからroleを取得するとき、めちゃくちゃめんどくさいし分かりづらい!
User::first()->roleUsers()->first()->role()->first()
Pivotを使う場合
Models/RoleUser.php
use Illuminate\Database\Eloquent\Relations\Pivot;
class RoleUser extends Pivot
{
...
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function role(): BelongsTo
{
return $this->belongsTo(Role::class);
}
}
Models/User.php
class User extends Model
{
...
public function roles(): BelongsToMany
{
return $this->belongsToMany(Role::class, 'role_user', 'user_id', 'role_id');
}
}
Models/Role.php
class Role extends Model
{
...
public function users(): BelongsToMany
{
return $this->belongsToMany(User::class, 'role_user', 'user_id', 'role_id');
}
}
userからroleを取得するとき下記のようにしたら取得できるので、シンプルで分かりやすい!
User::first()->roles()
参考