staudenmeir / laravel-merged-relations

Merged Laravel Eloquent relationships
MIT License
175 stars 11 forks source link

Using withPivot over a merge of different pivottables #20

Open erikjandelange opened 1 month ago

erikjandelange commented 1 month ago

I'm unable to use withPivot() in mergeRelation when use two different pivot tables.

Code to replicate:

Using pivot-tables:

App\Models\User.php

public function followedProjects(): BelongsToMany
{
    return $this->belongsToMany(Project::class, 'project_follower', 'follower_id', 'project_id');
}

public function assignedProjects(): BelongsToMany
{
    return $this->belongsToMany(Project::class, 'project_designer', 'designer_id', 'project_id');
}

Migration to create view

use Staudenmeir\LaravelMergedRelations\Facades\Schema;

Schema::createMergeView(
    'followers',
    [
        (new User)->followedProjects()->withPivot('sorting'),
    ]
);
Schema::createMergeView(
    'designers',
    [
        (new User)->assignedProjects()->withPivot('sorting')
    ]
);
Schema::createMergeView(
    'all',
    [
        (new User)->followedProjects()->withPivot('sorting'),
        (new User)->assignedProjects()->withPivot('sorting')
    ]
);

The view followers has a column: __project_follower__pivot__sorting. The view designers has a column: __project_designer__pivot__sorting.

But the view all doesn't have any extra columns. It's probably because the names of the columns in followers and designers doesn't match.

If this is the case, maybe give the columns an alias to use in the field?

staudenmeir commented 1 month ago

Hi @erikjandelange, I'll look into it. Try this workaround until different pivot tables are supported: https://github.com/staudenmeir/laravel-merged-relations/issues/10#issuecomment-1182753771