Empty hasOne relation should return null instead of {} when serialized #1839
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.
Introduction
When fetching a model that has a
hasOne
relation and that relation doesn't exist the relation should benull
when serializing the model. Currently it's an empty object{}
.Motivation
This makes the
hasOne
relationship behave likebelongsTo
which also exhibited this same unexpected behavior until it was changed with PR #1563. All other relation types continue working the same way, so ahasMany
without any records is still an empty array[]
when serialized.This should make it easier to determine if a
hasOne
relation exists or not since after serialization you can just write:instead of:
Proposed solution
This changes the eager pairing code to ensure that the relation creation part is skipped if the response from the
SELECT
query that tries to fetch the related data is empty. The eager pairing would runpushModels()
which would always create relation data on the parent model, even when there is no data, resulting in the empty object that was present before this change.This is a behavior similar to the
belongsTo
relation, except that that one can be determined much earlier in the eager loading code chain.Fixes #1771.
Current PR Issues
This is a breaking change, but it shouldn't cause too much trouble since any existing conditions, as in the example above, will still continue working. Other use cases that attempt to add or read properties directly from the serialized output will break.