-
Notifications
You must be signed in to change notification settings - Fork 11.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[5.4] Macroable relations #17707
[5.4] Macroable relations #17707
Conversation
Hello @thecrypticace. I read the post about this feature here: https://laravel-news.com/relationship-macros But I'm wondering if something like:
Does not achieve the same? I'd like to understand this better because I'd like to talk about it, so I'd appreciate if you send me or post other links or examples about this feature. |
The code snippet you have does indeed achieve the same thing. However, the example of a In a simple case like the above I would still prefer the use of |
thank you, @thecrypticace. I was just curious about other examples / use cases. |
@thecrypticace hi, also saw the post in the LN newsletter. Do you have an example of the "However, the example of a toHasOne macro is useful when you have an existing relationship with additional constraints on it (where clauses, orders, etc…) especially if any of them happen to be non-trivial." case so we can understand when this should be usefull? |
I would like to create MorphToMany to toHasOne but it does not work. MorphToMany::macro('toHasOne', function() {
return new HasOne(
$this->query,
$this->parent,
$this->foreignKey,
$this->localKey
);
}); |
I'd like to be able to do this for a Something like: BelongsToMany::macro('toHasOne', function() {
return new HasOne(
$this->query,
$this->parent,
$this->foreignKey,
$this->relatedKey
);
}); |
Afaik there'd be no way to convert a many-to-many relationship into a one-to-one relationship. One side has to be constrained by a single model. |
Does what it says on the tin. Makes relations
Macroable
so one could, say, add atoHasOne
method toHasMany
without subclassing it.h/t to @adamwathan for getting the gears turning on this idea.