是否可以在 Laravel 中的同一模型上建立多对多变形关系? (由关系变形的两个在同一个模型中)

Is it possible to make many-to-many morphed relation on same model in Laravel? (Two morphed by relations are in the same Model)

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

Roles
id | name

DocTypes
id | name | author_id | approved

docTypes_roles_table
doc_type_id | role_id| role_type

这是我的代码:

在 AppServiceProvider 中 Class:

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

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

角色 Class

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

在 DocType 中 Class

/**
     * 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() 时,它会保存到数据库 'approve' 类型。

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

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

我通过将 Role class 扩展到另一个 CreatorRole class 来做到这一点。 但是现在,如果我需要这样的东西,我会添加另一列(例如 'type')到枢轴 table 并按此枢轴值进行附加。