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

Incorrect join if alias is used #15

Closed
nerg4l opened this issue Nov 29, 2018 · 2 comments
Closed

Incorrect join if alias is used #15

nerg4l opened this issue Nov 29, 2018 · 2 comments

Comments

@nerg4l
Copy link

nerg4l commented Nov 29, 2018

Hi!

If I have something like the following:

class Post extends Model
{
    public function similar()
    {
        return $this->hasManyDeep(
            self::class,
            ['taggable as alias', Tag::class, 'taggable']
        );
    }
}

The following sql is generated:

select "posts".*, "taggable" as "alias.post_post_pk"
from "posts"
       inner join "taggable" on "taggable"."post_post_pk" = "posts"."post_pk"
       inner join "tags" on "tags"."tag_pk" = "taggable"."tag_tag_pk"
       inner join "taggable" as "alias" on "taggable" as "alias.tag_tag_pk" = "tags"."tag_pk"
where "taggable" as "alias.post_post_pk" = 1

As you can see the "taggable" as "alias.tag_tag_pk" is the problematic part.

The error first occurs in HasManyDeep:110 as inside Model::qualifyColumn $this->getTable() returns project_category as alias. Then $this->getQualifiedFirstKeyName() returns the same so when the where is added this generates the wrong alias.

Edit: Example is replaced with Models from the test of this package.

@staudenmeir
Copy link
Owner

As the documentation mentions, you have to use the HasTableAlias trait in the model you are aliasing.

In this case, it's a bit more complicated. Create a pivot model for the taggable table:

class Taggable extends \Illuminate\Database\Eloquent\Relations\Pivot
{
    use \Staudenmeir\EloquentHasManyDeep\HasTableAlias;

    protected $table = 'taggable';
}

Then use it like this:

class Post extends Model
{
    public function similar()
    {
        return $this->hasManyDeep(
            self::class,
            [Taggable::class.' as alias', Tag::class, 'taggable']
        );
    }
}

@nerg4l
Copy link
Author

nerg4l commented Nov 29, 2018

Oh, so sorry I missed that.

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