Accessor(Getter)和Mutators(Setter)在Laravel的数据透视表上

ATL*_*ris 9 php pivot-table laravel eloquent

我有一个将用户连接到工作区的数据透视表.在数据透视表上,我还有一个role列,它定义了该工作空间的用户角色.我可以在数据透视表中的角色上提供Accessor(Getter)和Mutator(Setter)方法吗?我一直在努力寻找,但是雄辩的数据透视表的细节非常稀少.

我不确定是否必须设置自定义枢轴模型?如果我这样做,一个例子将是非常棒的,因为关于枢轴模型的文档非常基础.

谢谢.

pat*_*cus 10

如果您只需访问数据透视表上的其他字段,则只需withPivot()在关系定义上使用该方法:

class User extends Model {
    public function workspaces() {
        return $this->belongsToMany('App\Models\Workspace')->withPivot('role');
    }
}

class Workspace extends Model {
    public function users() {
        return $this->belongsToMany('App\Models\User')->withPivot('role');
    }
}
Run Code Online (Sandbox Code Playgroud)

现在您的角色字段将在数据透视表中可用:

$user = User::first();

// get data
foreach($user->workspaces as $workspace) {
    var_dump($workspace->pivot->role);
}

// set data
$workspaceId = $user->workspaces->first()->id;
$user->workspaces()->updateExistingPivot($workspaceId, ['role' => 'new role value']);
Run Code Online (Sandbox Code Playgroud)

如果您确实需要为数据透视表创建访问器/更改器,则需要创建自定义数据透视表类.我之前没有这样做过,所以我不知道这是否真的有用,但看起来你会这样做:

创建一个包含访问者/ mutator的新pivot类.此类应扩展默认的Pivot类.这个新类是当User或Workspace创建Pivot模型实例时将要实例化的类.

namespace App\Models;
use Illuminate\Database\Eloquent\Relations\Pivot;
class UserWorkspacePivot extends Pivot {
    getRoleAttribute() {
        ...
    }
    setRoleAttribute() {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,更新您的用户和工作区模型以创建此新的数据透视表类,而不是默认的类.这是通过重写newPivot()Model类提供的方法来完成的.您希望覆盖此方法,以便创建新UserWorkspacePivot类的实例,而不是默认的Pivot类.

class User extends Model {
    // normal many-to-many relationship to workspaces
    public function workspaces() {
        // don't forget to add in additional fields using withPivot()
        return $this->belongsToMany('App\Models\Workspace')->withPivot('role');
    }

    // method override to instantiate custom pivot class
    public function newPivot(Model $parent, array $attributes, $table, $exists) {
        return new UserWorkspacePivot($parent, $attributes, $table, $exists);
    }
}

class Workspace extends Model {
    // normal many-to-many relationship to users
    public function users() {
        // don't forget to add in additional fields using withPivot()
        return $this->belongsToMany('App\Models\User')->withPivot('role');
    }

    // method override to instantiate custom pivot class
    public function newPivot(Model $parent, array $attributes, $table, $exists) {
        return new UserWorkspacePivot($parent, $attributes, $table, $exists);
    }
}
Run Code Online (Sandbox Code Playgroud)