[7.x] Add extendable relations for models #33025
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.
This PR introduces the
resolveRelationUsing
method, which allows defining relationships between models from "outside" of the classes. For example:This extension could be very handy when building multiple packages in the same ecosystem that may extend each other's functionality. Of course often extending models, using traits or writing query builder macros is enough, but all of them have limitations at some point.
Keys should be passed explicitly when defining the relationship, to avoid automatically generated keys for a closure:
{closure}_id
.By default, this should not be a breaking change, at least I could not find any. However, any defined resolvers will be triggered before the call is forwarded to the query builder. But by default, this should not affect any existing code, since the resolvers array is empty.
Also, this would not affect any property or method that the class already has, they should have priority over the relation definitions.
I found a related PR #22507, however, this approach tries to achieve to provide the same behavior as it would be a "native" relation definition. Also, the implementation of the two PRs are quite different.