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

fix for HasManyThrough returning incorrect results with chunk() and each() (#21774) #24090

Closed
wants to merge 1 commit into from

Conversation

AmmarRahman
Copy link

Laravel Version: 5.5.40
PHP Version: 7.1.3 (MacOS 10.13.4)

Description:

Summary:
This is pull request addresses the issues reported on #21774. Using the chunk() method on a HasManyThrough relation object returns incorrect results. This is due to to the fact that Eloquent QueryBuilder attempts to hydrate the the related model with intermediate model attributes.

When querying models through a hasManyThrough relationship and using chunk() on the query, all the retrieved models have the same id (and probably a non-existent id for the model), even though their other attributes have the correct values. It creates a problem when eager loading other relations, since they all have the same id.
The aforementioned issue is a resulted because the intermediate model id is inserted on the query instead of the related model.

With the current codebase get() method has fixes the issue by getting an instance of the builder with the correct table and columns selected to overcome the issue. This can be demonstrated by the different model structure that would be retrieved when running
$country->posts()->get() vs $country->posts()->getQuery()->get()

The same issue is manifested when using each() method. This is because each() uses the underlying chunk() method during its runtime.

Proposed fix

chunk() and each() methods were added to HasManyThrough class to correct the selection of columns before they operate. This would contain the behaviour change to HasManyThrough without affecting any other behaviours. Hence, there are no breaking changes introduced.

Tests

Added two extra tests to DatabaseEloquentHasManyThroughIntegrationTest to test chunk() and each(), where the models are checked to have the correct columns defined.

@taylorotwell
Copy link
Member

Please send this to 5.6 branch first then I can help move it back to 5.5. Thanks.

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