1

Is there a way to get raw/unformatted values for a field before they're passed to the field's normalizeValue function? That is, get the value close to how it's stored in the database? I haven't found a documented method for this in the documentation.

Background

I'm building a section with a categories field, the selected categories act as filters for an entries feed that is displayed on the frontend for that entry. So I'm doing something like this:

{% set selectedCategories = entry.my_categories_field.ids() %}
{% set entriesFeed = craft.entries().relatedTo(selectedCategories).all() %}

But the additional database query is kind of pointless. As far as I know, the categories field already stores the selected categories as a list of IDs – correct me if I'm wrong. So when the field is accessed, it returns a CategoryQuery populated with a filter to match those IDs. Then I execute that query with .ids() just to get the IDs from the database that are already stored in the field in the first place.

Is there a simple way to get the stored IDs for that field directly without an additional database query? I.e., the value before its normalized to a CategoryQuery by normalizeValue?

1 Answer 1

2

I might be misunderstanding but if your my_categories_field is a Categories field then dump {{ dump(entry.my_categories_field) }} and you'll see that the ids aren't there.

Relations are stored in the relations table and are fetched using sourceId and fieldId.

From what I can see, you are on an entry page so what you could do if you wanted to lighten things up a little is to eager-load your categories:

{% do craft.app.elements.eagerLoadElements(
    className(entry),
    [entry],
    ['my_categories_field']
) %}

Then fetch your entries with:

{% set entriesFeed = craft.entries()
    .relatedTo(entry.my_categories_field)
    .all() %}

I'm not sure that's the answer but hopefully it helps :)

1
  • Awesome answer! So my assumption about how the categories field stores its data was indeed wrong, good to know. I'll take a look at the relations table to see how it works under the hood, definitely useful to know. Thanks for explaining!
    – MoritzLost
    Aug 17, 2021 at 8:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.