staudenmeir / eloquent-has-many-deep

Laravel Eloquent HasManyThrough relationships with unlimited levels
MIT License
2.67k stars 157 forks source link

Use hasManyDeepFromRelations on the same Model #151

Closed mariomarquesdev closed 2 years ago

mariomarquesdev commented 2 years ago

Hello, i'm having trouble creating a new relationship that uses hasManyDeepFromRelations.

Error SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'users'

I've tried to use HasTableAlias on User Model and Blog Model but it didn't work as expected

Expected result

Merge 3 relationships (user,creator,commenters) into one (participants). What i'm doing wrong here?

Blog Model

public function user(): BelongsTo
{
  return $this->belongsTo(User::class);
}

public function creator(): BelongsTo
{
    return $this->belongsTo(User::class);
}

public function commenters(): BelongsToMany
{
    return $this->belongsToMany(User::class, BlogComment::class)->distinct();
}

/**
 * Get participants.
 *
 * @todo: We should get the users who comments + creator + user
 * 
 * @return HasManyDeep
 */
public function participants(): HasManyDeep
{
    return $this->hasManyDeepFromRelations($this->commenters(), $this->user(), $this->creator());
}
staudenmeir commented 2 years ago

This is actually a misunderstanding of the package's purpose: It allows you to concatenate/chain relationships (A -> B -> C -> D) but not to merge them – that's a different (and more complicated) topic. I also created a package for this: https://github.com/staudenmeir/laravel-merged-relations

use Staudenmeir\LaravelMergedRelations\Facades\Schema;

Schema::createMergeView(
    'participants',
    [(new Blog)-> commenters(), (new Blog)-> user(), (new Blog)-> creator()]
);

class Blog extends Model
{
    use \Staudenmeir\LaravelMergedRelations\Eloquent\HasMergedRelationships;

    public function participants()
    {
        return $this->mergedRelationWithModel(User::class, 'participants');
    }
}
mariomarquesdev commented 2 years ago

Hello, my bad, i thought it would fit my needs. I've tried your solution and it almost worked, i created a new issue on your laravel-merged-relations: https://github.com/staudenmeir/laravel-merged-relations/issues/6