8000 HasManyThrough getQuery error · Issue #55738 · laravel/framework · GitHub
[go: up one dir, main page]

Skip to content
HasManyThrough getQuery error #55738
Closed
Closed
@mathieutu

Description

@mathieutu

Laravel Version

12.14.1

PHP Version

8.4

Database Driver & Version

Sqlite

Description

Hi,
When using HasManyThrough::getQuery (or toRawSql, or any other using to getQuery under the hood), the query used is wrong, because prepareQueryBuilder wasn't called.

The result in the case I have encounter is wrong models attributes fetch, especially with wrong ids (id attribute is coming from the table joined).

One solution could be to override getQuery in HasManyThrough class to call prepareQueryBuilder or shouldSelect (which contains the wanted logic).

protected function shouldSelect(array $columns = ['*'])
{
if ($columns == ['*']) {
$columns = [$this->related->qualifyColumn('*')];
}
return array_merge($columns, [$this->getQualifiedFirstKeyName().' as laravel_through_key']);

I can make the PR if you want.

WDYT?

Thanks,
Mathieu

Steps To Reproduce

With the example from the doc:

public function deployments(): HasManyThrough
{

     return $this->hasManyThrough(Deployment::class, Environment::class);

}

$this->deployments()->toRawSql() will return

select * from "deployments" inner join "environments" on "environments"."id" = "deployments"."environment_id" where "environment"."application_id" = XX

instead of

select "deployments".*, "environments"."application_id" as "laravel_through_key" from "deployments" inner join "environments" on "environments"."id" = "deployments"."environment_id" where "environment"."application_id" = XX

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0