Question:

How can I display related entries selected within a Matrix field?

Weston: 5 days ago

Consider an employee listing...

I have 2 sections: 1 for companies, 1 for personnel. In the personnel section, there is a matrix field within which one field is a relational one to relate the staff member to his company.

On the front end, I'm attempting to display a listing of all staff associated with a particular company.

I can't seem to get the relational fields to work in the way that I want. I know I'm missing something basic here.

{% set employer = craft.entries.section('companies').slug(segment) %}
{% set personnel = craft.entries.section('people').relatedTo(employer) %}

{% for x in personnel %}
    {{ x.title }}
{% endfor %}

// Output: nothing

Is there something particular to Matrix fields that changes how I might do this? I've tried using the targetElement parameter but still can't seem to get it to work.

Thanks for the help!

Answer:
Paisley: 5 days ago

When you relate an element from a Matrix block, it's important to know that the relation is between the Matrix block and the related element; nor the entry (or whatever has the Matrix field) and the related element.

So, the correct way to select related elements through a Matrix field is:

{% set employer = craft.entries.section('companies').slug(segment) %}
{% set personnel = craft.entries.section('people').relatedTo({
    targetElement: employer,
    field: "matrixField.relationField"
}) %}

Update: Added a missing } on the last line.