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

Lucas: 20 May 2022

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).

Lucy: 20 May 2022

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
    // replace with name of your image field; find only entries with images in your image field 

$assetsUsedInTeams = Asset::find()
        'element' => $teams,
        'field' => 'my_image_field',

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()
            'targetElement' => $asset,
            'field' => 'my_image_field'

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.