I have two entities, Post and Category
A Post belongs to a Category via a entity_reference field type name category_id
I want to get a count of posts belonging to a category (To prevent deleting a category that has posts)
My solution is this:
class PostDP{ private string entityTypeId = 'entity_post'; private EntityTypeManagerInterface $em; public function __construct(EntityTypeManagerInterface $em) { $this->em = $em; } public function getByCategoryId(int $categoryId): array { $query = $this->em->getStorage($this->entityTypeId)->getQuery();; $query->condition('category_id', $categoryId, '='); $result = $query->execute(); $posts = $this->em->getStorage($this->entityTypeId)->loadMultiple($result); return $posts; } }
Isn’t there another way to get just the count without loading all the posts ?