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

Add support for related instance table alias #115

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

toitzi
Copy link

@toitzi toitzi commented Feb 27, 2025

This PR aims to add support for also aliasing the related instance. This change is non breaking.

e.g:

class Comment extends Model
{
    use \Znck\Eloquent\Traits\BelongsToThrough;

    public function grandparent(): \Znck\Eloquent\Relations\BelongsToThrough
    {
        return $this->belongsToThrough(
            Comment::class . ' as relation', // -> THIS IS NEW
            Comment::class . ' as alias',
            foreignKeyLookup: [Comment::class => 'parent_id']
        );
    }
}

The reason for this is i have a belongsToThrough relation, which ends up at the model itself.
E.g. (Not really posts in my case just an example):

  1. A posts table
  2. A posts_relation table (which has a column "parent_post_id" and "post_id")

And now I have a post where i want to get it's parent post which is easy to archive thanks to this library, however when using it not only on a single post but on a collection, for example with "whereDoesNotHave" e.g "Posts::whereDoesNotHave('parentPost')", the query will not work, since the table names collide. Therefore aliasing on a releated table is needed.

@staudenmeir
Copy link
Owner

Hi @toitzi,
Thanks, I'll take a look.

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

Successfully merging this pull request may close these issues.

2 participants