0

我有带表格的 Role 和 DocType 模型。DocTypes 必须由特定角色批准,并由另一个特定角色创建。这是表结构:

Roles
id | name

DocTypes
id | name | author_id | approved

docTypes_roles_table
doc_type_id | role_id| role_type

这是我的代码:

在 AppServiceProvider 类中:

public function boot() {
 Schema::defaultStringLength(191);

 Relation::morphMap([
    'approve' => 'App\Models\Role',
    'create' => 'App\Models\Role',
 ]);
}

在角色类

public function docTypes() {
    return $this->morphToMany('App\Models\DocType', 'role','doc_type_role');
    }

在 DocType 类中

/**
     * Get the polymorphic relation with roles table
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphToMany
     */
    public function roles() {
        return $this->morphedByMany('App\Models\Role', 'role','doc_type_role')->withPivot('role_type');
    }

    /**
     * Get roles which must approve the docType
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphToMany
     */
    public function approveRoles() {
        return $this->roles()->wherePivot('role_type','approve')->withPivot('sequence')->orderBy('sequence');
    }

    /**
     * Get roles which create the docType
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphToMany
     */
    public function createRoles() {
        return $this->roles()->wherePivot('role_type','create');
    }

但是当我将角色附加到createRoles()它时,保存到数据库“批准”类型。

$trip = User::find(1)->docTypes()->create([
    "name"         => "business_trip",
    "display_name" => "Business Trip",
]);
$trip->approveRoles()->sync([
    2 => ['sequence' => 1],
]);

$trip->createRoles()->attach([5,3]);
4

1 回答 1

0

我通过将 Role 类扩展到另一个 CreatorRole 类来做到这一点。但是现在如果我需要这样的东西,我会在数据透视表中添加另一列(例如“类型”)并通过这个数据透视值进行附加。

于 2019-09-06T21:32:15.933 回答