[8.x] Add firstOr() function to BelongsToMany relation #40828
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.
What does this PR do?
firstOr()
function to theBelongsToMany::class
relationship.Why do we need this?
Before this PR
The 'firstOr()' function was being executed via the
__call()
method of theBelongsToMany::class
which forwarded the call to theEloquent\Builder::class
. When thefirstOr()
function found afirst()
record it returned the relationship instance, but didn't add the necessary select columns ($this->shouldSelect($columns)
) to the query builder object.With this PR
By adding the
firstOr()
function to theBelongsToMany::class
itself, theget()
that executes the select query statement is now the one that lives in theBelongsToMany::class
and defines the columns that should be selected.Thanks to the
get()
function being executed directly on theBelongsToMany::class
's relation, it adds the select columns, and prevents thePost::class
's model from inheriting the wrongid
and/or any other pivot table (users_posts
) column with the same name as any of the columns in theposts
table.