Skip to content
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

craft.hyper.getRelatedElements vs <handle>.getAllElements vs. with(...) #228

Open
hiasl opened this issue Jan 29, 2025 · 1 comment
Open
Labels

Comments

@hiasl
Copy link

hiasl commented Jan 29, 2025

Question

We (and I guess others as well) need all related elements of a certain hyper field (let's call it hyperFieldHandle)

It is possible to get them either

  • by using craft.hyper.getRelatedElements(...)
  • or by manually extracting all IDs using e.g. set ids = entry.hyperFieldHandle|map(e => e.id) (that gives me all related IDs), which I forward to an element query els = craft.entries().ids(ids).collect() and then I can use els.find(<myCurrentId>) to catch the corresponding element while iterating hyper rows.

Why don't you provide a method on the field object, which does the second solution in one Call and assigns each element to each Hyper result row? With an option to provide the "select(...)" for the query being used to fetch them? That would be eager loading for related elements :-).
Or even use .with('hyperFieldHandle') in element queries to trigger that?

Or am I missing something here and think that's too easy?

Additional context

No response

@hiasl hiasl added the question label Jan 29, 2025
@engram-design
Copy link
Member

We can't use .with('hyperFieldHandle') because the value of Hyper fields aren't elements. In fact, doing that will cause an issue, so I'd recommend not to do that.

I suppose the only reason we don't provide a entry.hyperFieldHandle.getElements() function which would return an array of linked-to elements - is that not every Hyper link is element-based. This might lead to a little confusion, as they indexes of elements won't follow the same count as links.

For example, you could have 2 entry links, 1 URL and 1 category link. Calling a entry.hyperFieldHandle.getElements() function would return an array of 3 Element objects, which can be misleading depending on what you're doing. You couldn't look at the 3rd Hyper link and match it to the 3rd related element.

But again, it depends what you're doing. If you want to add eager-loading in this fashion by extracting the elements a Hyper field is using, you can do that, but you're probably going to cause more overhead than benefit due to how Hyper already handles cached data for elements that links link to.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants