加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

php – Accessors(Getter)和Mutators(Setter)在Laravel的数据透

发布时间:2020-12-14 19:47:15 所属栏目:大数据 来源:网络整理
导读:我有一个将用户连接到工作区的数据透视表.在数据透视表上,我还有一个role列,它定义了该工作空间的用户角色.我可以提供Accessor(Getter) Mutator(Setter)方法对pivot表内的角色有何影响?我一直在试图看一遍,但雄辩的数据透视表的细节非常稀少. 我不确定是否
我有一个将用户连接到工作区的数据透视表.在数据透视表上,我还有一个role列,它定义了该工作空间的用户角色.我可以提供Accessor(Getter)& Mutator(Setter)方法对pivot表内的角色有何影响?我一直在试图看一遍,但雄辩的数据透视表的细节非常稀少.

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

谢谢.

如果您只需访问数据透视表上的其他字段,则只需在关系定义中使用withPivot()方法:
class User extends Model {
    public function workspaces() {
        return $this->belongsToMany('AppModelsWorkspace')->withPivot('role');
    }
}

class Workspace extends Model {
    public function users() {
        return $this->belongsToMany('AppModelsUser')->withPivot('role');
    }
}

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

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

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

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

namespace AppModels;
use IlluminateDatabaseEloquentRelationsPivot;
class UserWorkspacePivot extends Pivot {
    getRoleAttribute() {
        ...
    }
    setRoleAttribute() {
        ...
    }
}

现在,更新User和Workspace模型以创建此新的数据透视表类,而不是默认的类.这是通过重写Model类提供的newPivot()方法完成的.您希望覆盖此方法,以便创建新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('AppModelsWorkspace')->withPivot('role');
    }

    // method override to instantiate custom pivot class
    public function newPivot(Model $parent,array $attributes,$table,$exists) {
        return new UserWorkspacePivot($parent,$attributes,$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('AppModelsUser')->withPivot('role');
    }

    // method override to instantiate custom pivot class
    public function newPivot(Model $parent,$exists);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读