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 ?
Actually, I want to start from the Category
entity, And just check the count of related posts to a certain category.
Like in this (incomplete) example:
class CategoryDP{
private string entityTypeId = 'entity_category';
private EntityTypeManagerInterface $em;
public function __construct(EntityTypeManagerInterface $em)
{
$this->em = $em;
}
public function getCountPosts(int $categoryId): array
{
$query = $this->em->getStorage($this->entityTypeId)->getQuery();
/**
*@todo Get count posts
* Build a query that execute the SQL:
*
* SELECT
* count(*)
* FROM
* category c LEFT JOIN post p
* ON
* p.category_id = c.id
* WHERE
* c.id = :categoryId
*/
return $count;
}
}