简体   繁体   English

数据透视表上的 Laravel 访问器和修改器

[英]Laravel Accessors & Mutators on pivot table

I have many-to-many relationship in my models and I want to use Accessors & Mutators on my pivot table, but it seems not working我的模型中有多对多关系,我想在数据透视表上使用 Accessors & Mutators,但它似乎不起作用

User Model用户模型

public function roles()
{
    return $this->belongsToMany(Role::class,UserRole::class)
        ->withPivot('faculty_id', 'status');
}

UserRole Model用户角色模型

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;
    }
}

and in my controller I use for example在我的控制器中我使用例如

$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]);

Can I change 'teacher' to 2 using Accessors & Mutators ?我可以使用 Accessors & Mutators 将“老师”更改为 2 吗?

The second argument of belongsToMany() is for the table name, not the custom pivot model. belongsToMany()的第二个参数是表名,而不是自定义数据透视模型。 Use using() instead.使用using()代替。

You also need to add role_id to the withPivot call:您还需要将role_id添加到withPivot调用中:

public function roles()
{
    return $this->belongsToMany(Role::class)->using(UserRole::class)
        ->withPivot('faculty_id', 'status', 'role_id');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM