Php Laravel访问器和;透视表上的变数
我的模型中有多对多关系,我想在透视表中使用访问器和变异器,但它似乎不起作用 用户模型Php Laravel访问器和;透视表上的变数,php,laravel,eloquent,accessor,mutators,Php,Laravel,Eloquent,Accessor,Mutators,我的模型中有多对多关系,我想在透视表中使用访问器和变异器,但它似乎不起作用 用户模型 public function roles() { return $this->belongsToMany(Role::class,UserRole::class) ->withPivot('faculty_id', 'status'); } 用户角色模型 public function getRoleIdAttribute($role) { if($role ==
public function roles()
{
return $this->belongsToMany(Role::class,UserRole::class)
->withPivot('faculty_id', 'status');
}
用户角色模型
public function getRoleIdAttribute($role) {
if($role == 1) {
return "admin";
} else if($role == 2){
return "teacher";
} else if($role == 3){
return "student";
}
return null;
}
public function setRoleIdAttribute($role)
{
if($role == 'admin') {
$this->attributes['role_id'] = 1;
} else if($role == 'teacher') {
$this->attributes['role_id'] = 2;
} else if($role == 'student') {
$this->attributes['role_id'] = 3;
}
}
在我的控制器中,我使用
$user = User::create([
'first_name' => $request->first_name,
'middle_name' => $request->middle_name,
'last_name' => $request->last_name,
'email' => $request->email,
'password' => Hash::make($request->password)
]);
$user->roles()->attach('teacher', ['faculty_id' => $faculty]);
我可以使用accessor和Mutators将'teacher'更改为2吗?belongstomy()的第二个参数用于表名,而不是自定义透视模型。改用 您还需要将
role\u id
添加到withPivot
调用:
public function roles()
{
return $this->belongsToMany(Role::class)->using(UserRole::class)
->withPivot('faculty_id', 'status', 'role_id');
}