0

I have a reviews section with an entry field to Commerce products. I'm trying to show the reverse relationship review on the product page. It appears to work when there are related entries but when there are no related entries it appears to show random results. How can I show related reviews and no others?

{% set relatedReviews = craft.entries({
    section:        'reviews',
    orderBy:         'postDate desc',
    relatedTo:       product
}) %}

{% if relatedReviews %}
{% for relate in relatedReviews %}
   ...
{% endfor %}
{% endif %}

1 Answer 1

1

You shouldn't get random entries when no related entries were found. Relation queries add a where condition that limits what entries can be returned – if no related entries exist, the query will return nothing.

The most likely explanation is that the reviews are related to the products through some other field. In this case, you can limit the relatedTo query further by using the hash syntax to only include results where the product is the targetElement, and also limit the query to a specific field:

{% set relatedReviews = craft.entries({
    section: 'reviews',
    orderBy: 'postDate DESC',
    relatedTo: {
        targetElement: product,
        field: 'related_product',
    }
}) %}

Replace related_product with the handle of the field on the reviews section where the product is selected.

For a multi-site, you can also limit the query further by sourceSite.

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.