staudenmeir / belongs-to-through

Laravel Eloquent BelongsToThrough relationships
MIT License
1.15k stars 88 forks source link

Call to undefined method Znck\Eloquent\Relations\BelongsToThrough::is() #104

Closed emilebourquin closed 1 day ago

emilebourquin commented 3 days ago

Is it possible to have this fantastic library support the ComparesRelatedModels trait, like BelongsTo does?

Dropping the ComparesRelatedModels trait into BelongsToThrough throws the fatal error:

Class Znck\Eloquent\Relations\BelongsToThrough contains 2 abstract methods and must therefore be declared abstract or implement the remaining methods (Znck\Eloquent\Relations\BelongsToThrough::getParentKey, Znck\Eloquent\Relations\BelongsToThrough::getRelatedKeyFrom) in /var/www/html/vendor/staudenmeir/belongs-to-through/src/Relations/BelongsToThrough.php on line 22

staudenmeir commented 3 days ago

Hi @emilebourquin, It's not possible to support the trait in deep relations like BelongsToThrough.

Consider the example from the README: $post->country()->is($country) wouldn't work because the method can't know the value of users.country_id, but that's the foreign key it needs to compare with $country->id. It works for BelongsTo relationships because there aren't any intermediate tables.

staudenmeir commented 3 days ago

BelongsToThrough could override is() and execute a query to compare the related models, but I'm not sure that's a good idea. In the trait's PR, the author wrote that the whole point was that it doesn't require an additional query.

emilebourquin commented 1 day ago

Thank you for considering it, Jonas, I knew you'd have better insight as to whether this was possible. Having the ->is() function is handy for testing, but is not a show-stopper for me. Thank you for your very useful library.