[8.x] Add firstOr() function to BelongsToMany relation - #40828
Conversation
|
Please send this to 9.x |
I could do that, but won't 8.x be receiving bug fixes anymore? |
|
@r-kujawa this is a new feature, not a bug fix? |
|
@driesvints I believe it is a bug fix, because if you call the e.g. If the If the pivot table in the above query has an |
|
Here is a reference from somebody else experiencing this issue, hope it helps. |
|
@r-kujawa you're correct! Sorry about that. |
No worries, always happy to help 😄 |
|
This was actually already on 9.x back in September. |
What does this PR do?
firstOr()function to theBelongsToMany::classrelationship.Why do we need this?
Before this PR
The 'firstOr()' function was being executed via the
__call()method of theBelongsToMany::classwhich 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::classitself, theget()that executes the select query statement is now the one that lives in theBelongsToMany::classand 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 wrongidand/or any other pivot table (users_posts) column with the same name as any of the columns in thepoststable.