9

Sorry if this has been asked before. I've searched for other relatedTo questions but could not find anything similar.

I have 2 sections (each having 1 entry type):

  • games
  • reviews

Games are linked to 1 or more categories using a Categories field. Reviews are linked to 1 or more games using an Entries field.

On a category page I can list all related games using:

craft.entries({section: 'games'}).relatedTo(category)

I do however want to list all games inside a category that have at least 1 review. I tried something like

craft.entries({section: 'games'}).relatedTo(category).relatedTo(craft.entries.section('reviews'))

but that lists all games having a review regardless of the category. How to solve this?

  • Think I found the answer myself already. Maybe someone can confirm this is indeed the best way? {% paginate craft.entries({section: 'games'}) .relatedTo( 'and', category, {sourceElement: craft.entries({section: 'reviews'}), field: 'games'} ) .limit(8) as games %} – user155 Sep 1 '14 at 13:25
8

When you call this:

craft.entries({section: 'games'}).relatedTo(category).relatedTo(craft.entries.section('reviews'))

that second relatedTo param is just overriding the first one. Lucky for you, that parameter does accept multiple criteria (see the “Passing Multiple Relation Criteria” section on http://buildwithcraft.com/docs/relations#the-relatedTo-param).

{% set games = craft.entries({
    section: 'games',
    relatedTo: ['and',
        category,
        craft.entries.section('reviews').status(null)
    ]
}) %}

It's a good idea to specify that category will be a target element (where the Games entries did the selecting), and that the Reviews will be source elements (where the Games were selected by the Reviews), as this will slim the DB query down a bit:

{% set games = craft.entries({
    section: 'games',
    relatedTo: ['and',
        { targetElement: category },
        { sourceElement: craft.entries.section('reviews').status(null) }
    ]
}) %}
  • Good to know that this is possible, Brandon! Thanks also for the advise to use targetElement / sourceElement to slim down the DB query. Does it make sense to also include the field handle in the parameter to further reduce the load? – carlcs Sep 1 '14 at 13:37
  • Specifying the field handle won’t have much of an effect; it’s only necessary if you have more than one relational field between the elements and you want to filter the results to just pay attention to a particular field. – Brandon Kelly Sep 1 '14 at 14:03
  • I get a template error using the syntax above. Think it should be relatedTo: [...] ? – user155 Sep 1 '14 at 14:52
  • 2
    Sorry, yes. Fixed. – Brandon Kelly Sep 1 '14 at 14:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy