Skip to content

Getting an EAV option’s value (eav_attribute_option_value) instead of ID when fetching products using GraphQL

I should preface this by saying I know nothing about Magento 2 development, and barely anything about GraphQL, yet I’ve been added to this project so I have to learn both of them at the same time. I’ve spent a considerable amount of time trying to find a solution to my problem, but the only one I’ve been able to get working is inefficient.

We’ve got a GraphQL query to fetch a list of all products from a specific store. Part of the query is fetching the manufacturer, which is a custom EAV dropdown product attribute. The query I’m running is the following;

    ProductsForWebsites {
        items {
            total_items
            items {
                entity_id
                manufacturer
                name
                price
                sku
            }
            website { ... }
        }
    }
}

and in the resolver I’ve added 'manufacturer' to the addAttributeToSelect method;

$productCollection = $this->productCollectionFactory->create();
$productCollection->addAttributeToSelect([
    'sku',
    'name',
    'price',
    'manufacturer',
]);

This works, but instead of returning the option label (so the manufacturer name), it returns the option ID.

One solution I’ve found is to fetch the attributes for each item, find the one you need (manufacturer in my case) and call ->getFrontend()->getValue($item) to get the attributes value;

foreach ($items as $item) {
    $attributes = $item->getAttributes();
    $manufacturer = $attributes['manufacturer']->getFrontend()->getValue($item);

    ...
}

This once again works, but turns a ~4 second request into a timed out request because (I presume) it’s querying the database for every individual getValue call.

Is there a more efficient way of including the manufacturer’s name? I’ve tried a couple different ways of joining tables (joinAttributes(...), getSelect()->join(...)) but none of them work.

I understand the database structure; the attribute itself is stored in eav_attribute, its options in eav_attribute_option and the value for each option in eav_attribute_option_value, but I can’t figure out how to join this together in one efficient query, instead of N inefficient queries, in Magento 2/GraphQL.