1

I need some help. Really struggle understanding how to build relationships between channels/entries.

Context/Want: I have two separate channels: 1. "Plant catalogue" 2. "Plant care" I want to re-use the entries from "Plant catalogue" across the whole website wherever I need it accesing speicifc fields.

What I have: "Plant care" has an entries field type to help build the relationship with "Plant catalogue": field name: "plantEntity" "Plant catalogue" has an asset field that include a photo of the plant. fiel name: "plantPhoto"

My code so far:

{% set plantcareListing = craft.entries().section('plantCare').limit(null)%}
{% set entries = plantcareListing.all() %}

{% for entry in entries %}
  {% for image in entry.plantEntity %} {# how do I access the asset field "plantPhoto" here? :( #}
    <img src="{{ image.getUrl() }}" alt="{{ image.title }}">
  {% endfor %}

  {{ entry.title }}
{% endfor %}

I would appreciate your advice. Thank you!

1 Answer 1

2

It’s important to understand that using relations fields in the template works similar to using craft.entries. They return a element query object, for example entry.plantEntity in your entries loop. And you need to call the all() method on them to query for the elements. The same applies to querying for the asset elements in your inner entries loop.

{% set plantCares = craft.entries
    .section('plantCare')
    .all() %}

{% for plantCare in plantCares %}
    {% for plantEntity in plantCare.plantEntity.all() %}
        {% for plantPhoto in plantEntity.plantPhoto.all() %}
            <img src="{{ plantPhoto.getUrl() }}" alt="{{ plantPhoto.title }}">
        {% endfor %}

        {{ plantEntity.title }}
    {% endfor %}
{% endfor %}

You should generally avoid querying in a loop though, and use eager-loading instead.

{% set plantCares = craft.entries
    .section('plantCare')
    .with([
        'plantEntity',
        'plantEntity.plantPhoto'
    ])
    .all() %}

{% for plantCare in plantCares %}
    {% for plantEntity in plantCare.plantEntity %}
        {% for plantPhoto in plantEntity.plantPhoto %}
            <img src="{{ plantPhoto.getUrl() }}" alt="{{ plantPhoto.title }}">
        {% endfor %}

        {{ plantEntity.title }}
    {% endfor %}
{% endfor %}

If you’ve got many plantCare entries consider paginating through them.

2
  • Thank you so much carlcs! Works like magic and I now understand the concepts!
    – DorinV
    Feb 11, 2019 at 9:46
  • I’m glad it helped @DorinVancea, the docs on element queries are very good in my opinion.
    – carlcs
    Feb 11, 2019 at 13:37

Your Answer

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

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