How can I query a relation within Matrix via GraphQL #14546
-
I have products, and I have recipes. When I view a product, I want to show a recipe which mentions that product as one of its ingredients. The ingredients are currently modelled as a Matrix field How can I construct my GQL query to fetch recipe entries which refer to a given product in (at least) one of those matrix blocks? I have the relevant product's site ID, section, ID, and URI. To complicate it, the recipe type has another relation field which points to products, Do I want |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
There’s not a great way to do this right now. You could preload all the recipe + ingredient relations up front as part of your build pipeline, and reference that locally, if that’s an option. Otherwise, if you really need to find related recipes on the fly, you could add a “Combined Products” relation field to the Recipes section, and set its value dynamically when recipes are saved. use craft\base\Event;
use craft\elements\Entry;
use craft\events\ModelEvent;
use craft\fields\BaseRelationField;
Event::on(Entry::class, Entry::EVENT_AFTER_PROPAGATE, function(ModelEvent $event) {
/** @var Entry $entry */
$entry = $event->sender;
// is this entry in the Recipes section?
if ($entry->section?->handle === 'recipes') {
// get all the products related to its ingredients
$productIds = [];
foreach ($entry->ingredients->with('ingredient:product') as $ingredient) {
foreach ($ingredient->product as $product) {
$productIds[] = $product->id;
}
}
/** @var BaseRelationField $field */
$field = Craft::$app->fields->getFieldByHandle('combinedProducts', 'global');
Craft::$app->relations->saveRelations($field, $entry, $productIds);
}
}); In that code I’m assuming:
(Adjust accordingly.) You can even hide that “Combined Products” field from view for authors, by setting an admin-only condition on the field within the Recipe entry type’s field layout. With that in place, you could grab the related recipes using the |
Beta Was this translation helpful? Give feedback.
There’s not a great way to do this right now.
You could preload all the recipe + ingredient relations up front as part of your build pipeline, and reference that locally, if that’s an option.
Otherwise, if you really need to find related recipes on the fly, you could add a “Combined Products” relation field to the Recipes section, and set its value dynamically when recipes are saved.