[5.6] Fix MorphTo lazy eager loading #25240
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Collection::load()
uses the first model to get the relationships for lazy eager loading. This can cause problems onMorphTo
relationships when the related models differ in certain aspects:Example 1: Different relationships in
$with
(#16604)This fails because Eloquent tries to load the
user
relationship on$video
(as specified in$post
).Example 2: Different primary keys (#24654)
This fails because Eloquent tries to access the
videos.post_id
column (as specified in$post
).All this is caused by
HasRelationships::morphTo()
only callingmorphEagerTo()
on eager loading: On lazy eager loading,morphInstanceTo()
is used.We can fix the problem by always using a fresh model instance when getting the relationship in
Builder::getRelation()
. This mimics eager loading where the query builder is initialized with a fresh instance.The new integration test combines different primary keys and the usage of
$with
.Fixes #16604 and fixes #24654.