Loading all revisions with Drupal 8 Entity query

Submitted by charles on

This method is from a custom entity class. The revision_id needs to match your entity's revision entity key.

/**
 * Loads all the revisions for this entity.
 *
 * @return array|NULL
 *   Array of entity revisions, keyed by revision_id.
 *
 * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
 * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
 */
public function loadRevisions() {
  $storage = \Drupal::entityTypeManager()
    ->getStorage('custom_entity');

  $ids = $storage->getQuery()
    ->condition('id', $this->id())
    ->allRevisions()
    ->sort('revision_id', 'DESC')
    ->execute();

  return $ids ? $storage->loadMultipleRevisions(array_keys($ids)) : NULL;
}