Score:0

Get count of related entities

ye flag

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;
  }
}
Kevin avatar
in flag
https://www.drupal.org/docs/8/api/database-api/dynamic-queries/count-queries
berramou avatar
gb flag
`$count = $query->count()->execute();`
Dylan avatar
kr flag
This is also an option - https://www.drupal.org/project/entity_usage
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.