Replies: 1 comment
-
Two points of clarification:
However, keeping to the point, if you want to stick with the Laravel nomenclature for checking values, then you probably want something named Still, I agree that it would be nice to have that method in the core framework. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Eloquent\Collection
extends the baseCollection
class, making it easier to work with groups of models. But (unless I'm missing something, and I probably am), there's no "simple" way to determine if one Eloquent Collection has any of the same items as another.It's definitely possible to do — but it's not as straightforward as it could be:
User
model, whichBelongsToMany
relatedTeam
modelsThe problem with intersecting is that it has to loop through every
Team
in bothUser
's collections. "Users and teams" is a trivial example, but for large datasets this is very inefficient. We just want to know if they have a single one in common — after the first match, the function can return immediately.With a base Collection class, we could use the
hasAny()
method:But this isn't possible with
Eloquent\Collection
. It has several extended methods for working with Eloquent models, which can be wrangled to achieve the same end result (contains
,diff
,except
,intersect
,unique
), but they all process the entire result set.Of course, we could extract all keys from both collections, re-build a fresh base Collection with each, then perform the checks — but it's a shame to go the long-way round :) I'm happy to pop in a PR for this if I'm not missing anything obvious.
And a brief side note: only the
has()
collection method is documented, for some reasonhasAny()
isn't. Not sure why, maybe just an oversight?Beta Was this translation helpful? Give feedback.
All reactions