Skip to content

Simple aliases not working properly if getTable method is defined #34

@Tofandel

Description

@Tofandel

Quick example:

class RelatedItem extends Model {
    public function related()
    {
        return $this->morphTo('related');
    }
   
   // This causes the issue (but I don't control it as it's part of a lib)
    public function getTable()
    {
        return config('twill.related_table', 'twill_related');
    }
}
class Video extends Model {
    public function relatableItems(): MorphMany
    {
        return $this->morphMany(RelatedItem::class, 'related');
    }
}

Video::query()->joinRelation('relatableItems as relatable')->toRawSQL()

Which produces the following invalid SQL

select * from `videos` inner join `twill_related` as `relatable` on `twill_related`.`related_id` = `videos`.`id` and `twill_related`.`related_type` = 'video' where `videos`.`deleted_at` is null

Unknown column 'twill_related.related_id' in ON

Because the table is aliased, the resulting SQL should have been

select * from `videos` inner join `twill_related` as `relatable` on `relatable`.`related_id` = `videos`.`id` and `relatable`.`related_type` = 'video' where `videos`.`deleted_at` is null

This also happens with hasMany or qualifyColumn

public function questions(): HasMany
{
        $q = $this->hasMany(Block::class, 'blockable_id');
        return $q
            ->where($q->qualifyColumn('type'), 'survey-input')
}
inner join `twill_blocks` as `que` on `twill_blocks`.`blockable_id` = `elearning_surveys`.`id` and `twill_blocks`.`type` = 'survey-input'

VS expected

inner join `twill_blocks` as `que` on `que`.`blockable_id` = `elearning_surveys`.`id` and `que`.`type` = 'survey-input'

Metadata

Metadata

Labels

BugSomething isn't working

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions