Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use hasManyDeepFromRelations on the same Model #151

Closed
mariomarquesdev opened this issue Jan 17, 2022 · 2 comments
Closed

Use hasManyDeepFromRelations on the same Model #151

mariomarquesdev opened this issue Jan 17, 2022 · 2 comments

Comments

@mariomarquesdev
Copy link

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
Copy link
Owner

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
Copy link
Author

mariomarquesdev commented Jan 19, 2022

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: staudenmeir/laravel-merged-relations#6

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants