<p>You can use <a href="https://craftcms.com/docs/3.x/relations.html" rel="nofollow noreferrer">Relations</a> to find assets which are related to a set of entries (i.e. used in a field of the entries). Specifically, the <code>relatedTo</code> parameter allows you to limit an asset query to assets that are used in a specific entry or set of entries. One caveat is that you have to load the entries which contain the assets field first (at least as far as I can tell from the documentation).</p>
<p>So you need to queries, one to get all entries with assets on them and one to get all assets:</p>
<pre class="lang-php prettyprint-override"><code>$teams = Entry::find()
    // replace with the name of the section your asset field is used on
    -&gt;section('teams')
    // replace with name of your image field; find only entries with images in your image field 
    -&gt;my_image_field(':notempty:')
    -&gt;all();

$assetsUsedInTeams = Asset::find()
    -&gt;relatedTo([
        'element' =&gt; $teams,
        'field' =&gt; 'my_image_field',
    ])
    -&gt;all();
</code></pre>
<p>Now getting the titles of entries where the asset is used is slightly more involved. You can use the same approach, but you will probably need another query for each image to find related entries. For example:</p>
<pre class="lang-php prettyprint-override"><code>foreach ($assetsUsedInTeams as $asset) {
    $entriesContainingAsset = Entry::find()
        -&gt;relatedTo([
            'targetElement' =&gt; $asset,
            'field' =&gt; 'my_image_field'
        ])
        -&gt;all();
}
</code></pre>
<p>Not sure about that last query, might need some adjustments to work properly. Also, those are a lot of <a href="https://stackoverflow.com/questions/97197/what-is-the-n1-selects-problem-in-orm-object-relational-mapping">N+1 queries</a>, so once it's working as you want it to make sure to optimize your queries with <a href="https://craftcms.com/docs/3.x/dev/eager-loading-elements.html" rel="nofollow noreferrer">Eager-loading</a> and maybe add some caching as well.</p>

CC BY-SA 4.0
2021-04-15T11:27:45.420Z
Thank you for this response, this is extremely helpful. I did not realise that you can parse a set of entries into the targetElement param when using relatedTo()
Jake
CC BY-SA 4.0
2021-04-15T11:32:36.533Z
@Jake You're welcome! That info is a bit hidden, it's described under [Simple Relationships](https://craftcms.com/docs/3.x/relations.html#simple-relationships): _Passing an array of elements returns results relating to any one of the supplied items, meaning one or the other by default_
MoritzLost
CC BY-SA 4.0
2021-04-15T16:50:51.367Z
Ah I see it now, thanks for the link. I don't currently have the reputation required to make your answer the official one, but will do it when I can!
Jake
CC BY-SA 4.0
2021-04-15T18:21:24.583Z
@Jake Glad I could help! Upvoting requires 15 reputation, but accepting an answer does not, you should see a little gray checkbox below the up/downvote button you can use to mark the answer as accepted :)
MoritzLost
CC BY-SA 4.0
2021-04-16T21:36:42.820Z
My bad! Thanks again.
Jake
CC BY-SA 4.0
2021-04-14T15:07:08.060Z
2021-04-14T15:07:08.060Z
MoritzLost
<p>We have a channel of entries which all include the same asset field.</p>
<p>We are trying to fetch all assets that are actively in use, ergo the assets which have been linked to any of the entries in the channel via the specified asset field.</p>
<p>If possible we would also like to also get the title(s) of the entries to which the asset is linked, as part of the query.</p>
<p>This is happening in a module (PHP) not template (Twig).</p>
<p>Context: gallery of photos (assets) uploaded by teams (channel entries).</p>

<assets>
How to fetch all assets that are in use, via a specific field
# How to fetch all assets that are in use, via a specific field

(Asked by: username_0 on 2021-04-14)

We have a channel of entries which all include the same asset field.

We are trying to fetch all assets that are actively in use, ergo the assets which have been linked to any of the entries in the channel via the specified asset field.

If possible we would also like to also get the title(s) of the entries to which the asset is linked, as part of the query.

This is happening in a module (PHP) not template (Twig).

Context: gallery of photos (assets) uploaded by teams (channel entries).

**Tags:** assets


---

## 1 answers

### Answer by username_1 on 2021-04-14. Score: 1 | Accepted answer

You can use Relations to find assets which are related to a set of entries (i.e. used in a field of the entries). Specifically, the relatedTo parameter allows you to limit an asset query to assets that are used in a specific entry or set of entries. One caveat is that you have to load the entries which contain the assets field first (at least as far as I can tell from the documentation).
So you need to queries, one to get all entries with assets on them and one to get all assets:
$teams = Entry::find()
    // replace with the name of the section your asset field is used on
    ->section('teams')
    // replace with name of your image field; find only entries with images in your image field 
    ->my_image_field(':notempty:')
    ->all();

$assetsUsedInTeams = Asset::find()
    ->relatedTo([
        'element' => $teams,
        'field' => 'my_image_field',
    ])
    ->all();

Now getting the titles of entries where the asset is used is slightly more involved. You can use the same approach, but you will probably need another query for each image to find related entries. For example:
foreach ($assetsUsedInTeams as $asset) {
    $entriesContainingAsset = Entry::find()
        ->relatedTo([
            'targetElement' => $asset,
            'field' => 'my_image_field'
        ])
        ->all();
}

Not sure about that last query, might need some adjustments to work properly. Also, those are a lot of N+1 queries, so once it's working as you want it to make sure to optimize your queries with Eager-loading and maybe add some caching as well.

> **Comments:**
> **username_0**: Thank you for this response, this is extremely helpful. I did not realise that you can parse a set of entries into the targetElement param when using relatedTo()  
> **username_1**: @username_0 You're welcome! That info is a bit hidden, it's described under [Simple Relationships](https://craftcms.com/docs/3.x/relations.html#simple-relationships): _Passing an array of elements returns results relating to any one of the supplied items, meaning one or the other by default_  
> **username_0**: Ah I see it now, thanks for the link. I don't currently have the reputation required to make your answer the official one, but will do it when I can!  
> **username_1**: @username_0 Glad I could help! Upvoting requires 15 reputation, but accepting an answer does not, you should see a little gray checkbox below the up/downvote button you can use to mark the answer as accepted :)  
> **username_0**: My bad! Thanks again.  

---

