Search code examples
laravel-nova

Not able to define BelongsToMany relationship using same models with different type


I have Model Organization and User. There can be a buyer account manager and a seller account manager for an organization.

In organization the relationship is like :

public function managers() {
return $this->belongsToMany(User::class, 'organization_account_managers')->using('App\Model\Organization\OrganizationAccountManager')->withPivot(['account_manager_type']);    

}

In User the relationship is defined as:

public function accounts() 
{
    return $this->belongsToMany(Organization::class, 'organization_account_managers')
    ->using('App\Model\Organization\OrganizationAccountManager')
    ->withPivot(['account_manager_type']);
}

When attaching in Nova, have defined on Organization as:

BelongsToMany::make('Account Managers','managers', 'App\Nova\User')
->fields(function () {
    return [
        Select::make('Type','account_manager_type')
                ->options(AppOrganization::$account_manager_types)
                ->rules('required')
                ->displayUsingLabels()->sortable(),
   ];
})

The table structure is:

Schema::create('organization_account_managers', function (Blueprint $table) {
        $table->id();
        $table->foreignId('organization_id');
        $table->foreignId('user_id');
        $table->tinyInteger('account_manager_type');
        $table->timestamps();
});

Problem statement: A user can be both buyer account manager and seller account manager. But when i try to attach so, NOva gives me an error: This users is already attached.

Appreciate any idea on how to resolve this.


Solution

  • From version v3.23.0 Laravel Nova allows duplicate relations.

    BelongsToMany::make('Account Managers', 'managers', 'App\Nova\User')
        ->fields(function () {
            ...
        })
        ->allowDuplicateRelations()
    

    If you are using previous version you can try this workaround.