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

时间:2019-09-06 21:22:27

标签: php laravel many-to-many relation polymorphic-relationship

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

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

0 个答案:

没有答案