Question:

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

Answer:
Lucy: 20 May 2022

You can use Relations (https://craftcms.com/docs/3.x/relations.html) 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 (https://stackoverflow.com/questions/97197/what-is-the-n1-selects-problem-in-orm-object-relational-mapping), so once it's working as you want it to make sure to optimize your queries with Eager-loading (https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) and maybe add some caching as well.