[7.x] Add extendable relations for models#33025
[7.x] Add extendable relations for models#33025taylorotwell merged 3 commits intolaravel:7.xfrom iamgergo:7.x
Conversation
|
https://github.com/imanghafoori1/eloquent-relativity My package did the same job, but it was faced with a lot of hate and anger in laravel/ideas, sadly. |
|
@imanghafoori1 Nice, I did not know about that package. I'm sorry to hear. I really don't understand why. I find this very useful in some cases. |
|
@iamgergo You work is absolutely welcome, I had a long discussion about the idea long before about this. |
|
@iamgergo Thanks so much for this. Such a simple implementation with so much potential. |
|
@imanghafoori1 this makes perfect sense. I'm using an architecture in which the parent cannot know about the models of the sub-modules therefore i could not use traits. |
This PR introduces the
resolveRelationUsingmethod, 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.