<p>I doubt there is a good solution in twig but you can fetch the entries with php.</p>

<p>First you have to get all used asset Ids. So you'll check in the <code>relations</code> table for all used assets with your 2 fields and for entries with your section ids</p>



<pre><code>public function getAllAssetsRelatedToEntries(){
    // list the ids of the sections, so you need the id of news, information and events
    $sectionIds = [2, 7];
    // id of your insertedImage field
    $fieldIdMatrixContent = 6;
    // id of your imageGallery field
    $fieldIdImageGallery = 7;

    // fetches all assets that have a relation in the matrix field
    $imagesFromMatrixContent =  craft()-&gt;db-&gt;createCommand()
        -&gt;select('craft_relations.targetId')
        -&gt;from('relations')
        -&gt;join('matrixblocks', 'craft_matrixblocks.id = craft_relations.sourceId')
        -&gt;join('entries', 'craft_entries.id = craft_matrixblocks.ownerId')
        -&gt;where('craft_relations.fieldId = :fieldId', ['fieldId' =&gt; $fieldIdMatrixContent])
        -&gt;andWhere(['in', 'craft_entries.sectionId', $sectionIds])
        -&gt;queryColumn();

    // fetches all assets that are related with the ImageGallery Field
    $imagesFromNormalField = craft()-&gt;db-&gt;createCommand()
        -&gt;select('craft_relations.targetId')
        -&gt;from('relations')
        -&gt;where('craft_relations.fieldId = :fieldId', ['fieldId' =&gt; $fieldIdImageGallery])
        -&gt;join('entries', 'craft_entries.id = craft_relations.sourceId')
        -&gt;andWhere(['in', 'craft_entries.sectionId', $sectionIds])
        -&gt;queryColumn();

    return array_unique(array_merge($imagesFromMatrixContent,$imagesFromNormalField));
}
</code></pre>

<p>This will return you an array of all ids, thus you can build your paginate or other queries like you want and change the sort order or include other conditions</p>

<pre class="lang-twig prettyprint-override"><code>{% set allAssetIds = craft.pFplugin.getAllAssetsRelatedToEntries() %}
{% paginate craft.assets.id(allAssetIds).kind('image').limit('30') as pageInfo, usedPhotos %}
</code></pre>

<p>The next step will be to search the entries for each asset
</p>

<pre><code>public function getAllEntriesForAsset($assetId)
{
    // list the ids of the sections, so you need the id of news, information and events
    $sectionIds = [2, 7];
    // id of your insertedImage field
    $fieldIdMatrixContent = 6;
    // id of your imageGallery field
    $fieldIdImageGallery = 7;

    $entryIdsFromMatrix = craft()-&gt;db-&gt;createCommand()
        -&gt;select('craft_matrixblocks.ownerId')
        -&gt;from('relations')
        -&gt;join('matrixblocks', 'craft_matrixblocks.id = craft_relations.sourceId')
        -&gt;where('craft_relations.targetId = :assetId', ['assetId' =&gt; $assetId])
        -&gt;join('entries', 'craft_entries.id = craft_matrixblocks.ownerId')
        -&gt;andWhere('craft_relations.fieldId = :fieldId', ['fieldId' =&gt; $fieldIdMatrixContent])
        -&gt;andWhere(['in', 'craft_entries.sectionId', $sectionIds])
        -&gt;queryColumn();

    $entryIdsImageGallery = craft()-&gt;db-&gt;createCommand()
        -&gt;select('craft_relations.sourceId')
        -&gt;from('relations')
        -&gt;where('craft_relations.targetId = :assetId', ['assetId' =&gt; $assetId])
        -&gt;join('entries', 'craft_entries.id = craft_relations.sourceId')
        -&gt;andWhere(['in', 'craft_entries.sectionId', $sectionIds])
        -&gt;andWhere('craft_relations.fieldId = :fieldId', ['fieldId' =&gt; $fieldIdImageGallery])
        -&gt;queryColumn();

    return array_unique(array_merge($entryIdsFromMatrix,$entryIdsImageGallery));
}
</code></pre>

<p>In your template
</p>

<pre><code>{% set entriesForAsset = craft.pFplugin.getAllEntriesForAsset(asset.id) %}
{% for entry in craft.entries().id(entriesForAsset).order('title') %}
    {{ entry.id }} {{ entry.title }}
{% endfor %}
</code></pre>

<p>In total it could look like this I just did not use the paginate
</p>

<pre><code>{% set allAssetIds = craft.pFplugin.getAllAssetsRelatedToEntries() %}
{% for asset in craft.entries.id(allAssetIds).find() %}
    {{ asset.id }} {{ asset.title }}
    Entries for Image&lt;br&gt;
    {% set entriesForAsset = craft.pFplugin.getAllEntriesForAsset(asset.id) %}
        {% for entry in craft.entries().id(entriesForAsset).order('title') %}
        {{ entry.id }} {{ entry.title }}
    {% endfor %}
{% endfor %}
</code></pre>

CC BY-SA 3.0
2017-12-10T11:34:17.140Z
Thanks Robin, but I'm guessing that this code would need to be wrapped up in a plugin, which is beyond my skill set. It's not a multi language site, so no locale issues.
Paul Frost
CC BY-SA 3.0
2017-12-10T11:40:06.850Z
As a web developer you should not be afraid to learn something new. Especially when you offer websites for others. Creating a plugin only takes about 2-3 minutes. Go to pluginfactory.io, fill out the few lines and select the light switch for "variables" download and copy the files to your `craft/app/plugins` folder and copy my code into the variables file. There are plenty of instructions in there how to gain access and call the functions. If you want I can do it for you and give you a download link
Robin Schambach
CC BY-SA 3.0
2017-12-10T12:52:39.920Z
I've got the package from pluginfactory.io and am looking at the variables file and am now lost. I've had a look at some other plugins to see if I can work out how/where to paste your code examples but I'm not seeing anything like it.
I do want to learn how to make a plugin but my brain hurts at the moment after trying every permutation to get this working. Can you give me some more to help get me going.
Paul Frost
CC BY-SA 3.0
2017-12-10T13:30:50.067Z
Alright, check my edit: download the plugin from my google docs account, extract the files and copy the folder into your `craft/app/plugins` folder. Make sure to install the plugin before you try to use it
Robin Schambach
CC BY-SA 3.0
2017-12-10T18:16:06.353Z
I really appreciate your help with this one.
I'm not sure if my paginate code is still correct now?
It looks like it is pulling in all the images (including the Matrix field ones that were missing before) but for the ones that are in the Assets field (imageGallery) it's not listing the related entries that they appear in. The Matrix field (extendedContent.insertedImage) images are listing the related entries. I think I understand why, is the plugin is only looking at the insertedImage Matrix field?
Paul Frost
CC BY-SA 3.0
2017-12-10T18:28:31.200Z
You can fetch the ids from your ElementCriteriaModel and merge the array with the one from the plugin. I only search for those in the matrix.
Robin Schambach
CC BY-SA 3.0
2017-12-10T20:41:52.143Z
I worked out that I needed to change the paginate query to: {% paginate craft.assets.kind('image').limit('30') as pageInfo, usedPhotos %}
Paul Frost
CC BY-SA 3.0
2017-12-10T20:45:30.580Z
But you'll get all assets with that query not just the used one. If you want I can provide you the code to fetch only used images.
Robin Schambach
CC BY-SA 3.0
2017-12-11T08:44:57.867Z
I edited the code
Robin Schambach
CC BY-SA 3.0
2017-12-11T12:23:47.767Z
I've responded on the chat page, https://chat.stackexchange.com/rooms/70015/discussion-between-paul-frost-and-robin-schambach
Paul Frost
CC BY-SA 3.0
2017-12-12T16:53:34.373Z
After Robin spending a lot of time helping me I have a working solution based on the code above.
Paul Frost
CC BY-SA 3.0
2017-12-09T19:03:39.923Z
2017-12-11T08:45:48.463Z
2017-12-11T08:45:48.463Z
Robin Schambach
<p>I have a photo gallery that pulls in all entries and then finds the images within them and then displays them along with links to the entries that used that image.
Except, it's not pulling in the ones that are in a matrix field named extendedContent with a block type of insertedImage and a asset field named image.
A simplified version of the code I'm using is:</p>

<pre><code>{% set content = craft.entries({
    section: 'news,information,events',
    with: ['imageGallery','extendedContent.insertedImage:image']
}) %}

{% paginate craft.assets.relatedTo(content).order('elements.dateCreated desc').kind('image').limit(25) as pageInfo, usedPhotos %}

{# Loop through the array of assets #}
{% for imageGallery in usedPhotos %}  
    &lt;img src="{{ imageGallery.url }}"&gt;

    {# find all entries related to this asset #}
    {% set entry = craft.entries.relatedTo(imageGallery).order('title') %}
        {% for entry in entry %}
            {{ entry.title }}
        {% endfor %}  

{% endfor %}
</code></pre>

<p>Added: I'm guessing the issue is that the relationship of the image in the matrix field isn't to the entry but to the block it's in?
Does that mean that it's not possible to do what I want?</p>

<matrix><entrymodel><relatedto>
How to get all images from entries including Matrix field
# How to get all images from entries including Matrix field

(Asked by: username_0 on 2017-12-08)

I have a photo gallery that pulls in all entries and then finds the images within them and then displays them along with links to the entries that used that image.
Except, it's not pulling in the ones that are in a matrix field named extendedContent with a block type of insertedImage and a asset field named image.
A simplified version of the code I'm using is:
{% set content = craft.entries({
    section: 'news,information,events',
    with: ['imageGallery','extendedContent.insertedImage:image']
}) %}

{% paginate craft.assets.relatedTo(content).order('elements.dateCreated desc').kind('image').limit(25) as pageInfo, usedPhotos %}

{# Loop through the array of assets #}
{% for imageGallery in usedPhotos %}  
    

    {# find all entries related to this asset #}
    {% set entry = craft.entries.relatedTo(imageGallery).order('title') %}
        {% for entry in entry %}
            {{ entry.title }}
        {% endfor %}  

{% endfor %}

Added: I'm guessing the issue is that the relationship of the image in the matrix field isn't to the entry but to the block it's in?
Does that mean that it's not possible to do what I want?

**Tags:** matrix, entrymodel, relatedto


---

## 1 answers

### Answer by username_1 on 2017-12-09. Score: 2 | Accepted answer

I doubt there is a good solution in twig but you can fetch the entries with php.
First you have to get all used asset Ids. So you'll check in the relations table for all used assets with your 2 fields and for entries with your section ids
public function getAllAssetsRelatedToEntries(){
    // list the ids of the sections, so you need the id of news, information and events
    $sectionIds = [2, 7];
    // id of your insertedImage field
    $fieldIdMatrixContent = 6;
    // id of your imageGallery field
    $fieldIdImageGallery = 7;

    // fetches all assets that have a relation in the matrix field
    $imagesFromMatrixContent =  craft()->db->createCommand()
        ->select('craft_relations.targetId')
        ->from('relations')
        ->join('matrixblocks', 'craft_matrixblocks.id = craft_relations.sourceId')
        ->join('entries', 'craft_entries.id = craft_matrixblocks.ownerId')
        ->where('craft_relations.fieldId = :fieldId', ['fieldId' => $fieldIdMatrixContent])
        ->andWhere(['in', 'craft_entries.sectionId', $sectionIds])
        ->queryColumn();

    // fetches all assets that are related with the ImageGallery Field
    $imagesFromNormalField = craft()->db->createCommand()
        ->select('craft_relations.targetId')
        ->from('relations')
        ->where('craft_relations.fieldId = :fieldId', ['fieldId' => $fieldIdImageGallery])
        ->join('entries', 'craft_entries.id = craft_relations.sourceId')
        ->andWhere(['in', 'craft_entries.sectionId', $sectionIds])
        ->queryColumn();

    return array_unique(array_merge($imagesFromMatrixContent,$imagesFromNormalField));
}

This will return you an array of all ids, thus you can build your paginate or other queries like you want and change the sort order or include other conditions
{% set allAssetIds = craft.pFplugin.getAllAssetsRelatedToEntries() %}
{% paginate craft.assets.id(allAssetIds).kind('image').limit('30') as pageInfo, usedPhotos %}

The next step will be to search the entries for each asset

public function getAllEntriesForAsset($assetId)
{
    // list the ids of the sections, so you need the id of news, information and events
    $sectionIds = [2, 7];
    // id of your insertedImage field
    $fieldIdMatrixContent = 6;
    // id of your imageGallery field
    $fieldIdImageGallery = 7;

    $entryIdsFromMatrix = craft()->db->createCommand()
        ->select('craft_matrixblocks.ownerId')
        ->from('relations')
        ->join('matrixblocks', 'craft_matrixblocks.id = craft_relations.sourceId')
        ->where('craft_relations.targetId = :assetId', ['assetId' => $assetId])
        ->join('entries', 'craft_entries.id = craft_matrixblocks.ownerId')
        ->andWhere('craft_relations.fieldId = :fieldId', ['fieldId' => $fieldIdMatrixContent])
        ->andWhere(['in', 'craft_entries.sectionId', $sectionIds])
        ->queryColumn();

    $entryIdsImageGallery = craft()->db->createCommand()
        ->select('craft_relations.sourceId')
        ->from('relations')
        ->where('craft_relations.targetId = :assetId', ['assetId' => $assetId])
        ->join('entries', 'craft_entries.id = craft_relations.sourceId')
        ->andWhere(['in', 'craft_entries.sectionId', $sectionIds])
        ->andWhere('craft_relations.fieldId = :fieldId', ['fieldId' => $fieldIdImageGallery])
        ->queryColumn();

    return array_unique(array_merge($entryIdsFromMatrix,$entryIdsImageGallery));
}

In your template

{% set entriesForAsset = craft.pFplugin.getAllEntriesForAsset(asset.id) %}
{% for entry in craft.entries().id(entriesForAsset).order('title') %}
    {{ entry.id }} {{ entry.title }}
{% endfor %}

In total it could look like this I just did not use the paginate

{% set allAssetIds = craft.pFplugin.getAllAssetsRelatedToEntries() %}
{% for asset in craft.entries.id(allAssetIds).find() %}
    {{ asset.id }} {{ asset.title }}
    Entries for Image
    {% set entriesForAsset = craft.pFplugin.getAllEntriesForAsset(asset.id) %}
        {% for entry in craft.entries().id(entriesForAsset).order('title') %}
        {{ entry.id }} {{ entry.title }}
    {% endfor %}
{% endfor %}

> **Comments:**
> **username_0**: Thanks Robin, but I'm guessing that this code would need to be wrapped up in a plugin, which is beyond my skill set. It's not a multi language site, so no locale issues.  
> **username_1**: As a web developer you should not be afraid to learn something new. Especially when you offer websites for others. Creating a plugin only takes about 2-3 minutes. Go to pluginfactory.io, fill out the few lines and select the light switch for "variables" download and copy the files to your `craft/app/plugins` folder and copy my code into the variables file. There are plenty of instructions in there how to gain access and call the functions. If you want I can do it for you and give you a download link  
> **username_0**: I've got the package from pluginfactory.io and am looking at the variables file and am now lost. I've had a look at some other plugins to see if I can work out how/where to paste your code examples but I'm not seeing anything like it. I do want to learn how to make a plugin but my brain hurts at the moment after trying every permutation to get this working. Can you give me some more to help get me going.  
> **username_1**: Alright, check my edit: download the plugin from my google docs account, extract the files and copy the folder into your `craft/app/plugins` folder. Make sure to install the plugin before you try to use it  
> **username_0**: I really appreciate your help with this one. I'm not sure if my paginate code is still correct now? It looks like it is pulling in all the images (including the Matrix field ones that were missing before) but for the ones that are in the Assets field (imageGallery) it's not listing the related entries that they appear in. The Matrix field (extendedContent.insertedImage) images are listing the related entries. I think I understand why, is the plugin is only looking at the insertedImage Matrix field?  
> **username_1**: You can fetch the ids from your ElementCriteriaModel and merge the array with the one from the plugin. I only search for those in the matrix.  
> **username_0**: I worked out that I needed to change the paginate query to: {% paginate craft.assets.kind('image').limit('30') as pageInfo, usedPhotos %}  
> **username_1**: But you'll get all assets with that query not just the used one. If you want I can provide you the code to fetch only used images.  
> **username_1**: I edited the code  
> **username_0**: I've responded on the chat page, https://chat.stackexchange.com/rooms/70015/discussion-between-paul-frost-and-robin-schambach  
> **username_0**: After Robin spending a lot of time helping me I have a working solution based on the code above.  

---

