Search code examples
phplaravelmany-to-manyrelationpolymorphic-relationship

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


I have Role and DocType models with tables. DocTypes must be approved by the specific Roles, and created by another specific Roles. Here is the tables structure:

Roles
id | name

DocTypes
id | name | author_id | approved

docTypes_roles_table
doc_type_id | role_id| role_type

Here is my code:

in AppServiceProvider Class:

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

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

in Role Class

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

in 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');
    }

But when I attach the roles to createRoles() it save to database 'approve' type.

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

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

Solution

  • I did it by extending Role class to another CreatorRole class. But now if I need thing like this, I add another one column (ex. 'type') to pivot table and do attaching by this pivot value.