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

[5.8] Fix column overriding in HasManyThrough relationships #25812

Merged
merged 1 commit into from
Sep 28, 2018
Merged

[5.8] Fix column overriding in HasManyThrough relationships #25812

merged 1 commit into from
Sep 28, 2018

Conversation

staudenmeir
Copy link
Contributor

@staudenmeir staudenmeir commented Sep 27, 2018

When the related table of a HasManyThrough relationship contains a column with the same name as the $firstKey in the intermediate table (selected for eager loading), the intermediate value overrides the related value:

Schema::create('users', function ($table) {
    $table->increments('id');
});

Schema::create('teams', function ($table) {
    $table->increments('id');
    $table->integer('owner_id');
});

Schema::create('projects', function ($table) {
    $table->increments('id');
    $table->integer('owner_id');
});

class User extends Model
{
    public function projects()
    {
        return $this->hasManyThrough(Project::class, Team::class, 'owner_id', 'owner_id');
    }
}

User::with('projects')->get();

// Contains "teams.owner_id" instead of "projects.owner_id".
dump($users[0]->projects[0]->owner_id);

We can fix this by adding an alias to the $firstKey column (that hopefully nobody uses as a column name):

select "projects".*, "teams"."owner_id" as "_first_key"
from "projects" inner join "teams" on "teams"."id" = "projects"."owner_id"
where "teams"."owner_id" in (?)

There already are eager loading tests.

Fixes #17918.

@staudenmeir staudenmeir changed the title [5.8] Add column alias for $firstKey in HasManyThrough relationships [5.8] Fix column overriding in HasManyThrough relationships Sep 28, 2018
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.

None yet

2 participants